Playing around with UnderscoreJS templates

I was doing a project where I started using UnderscoreJS and find this real easy to use and a timesaver in projects. I also explored templates in underscoreJS and had some small issue’s that I would like to share here.

So I thought let’s share some findings when using templates and the utility functions for this library.

About Templates:
I find the templates a nice addition but you could definitly mis-use this and be tempted to put to much logic inside a template. Using a mixin or extending your Object by using _.extend or Jquery. Also there are a lot templating libs available. This list has usefull information about templating solutions, when in doubt picking a solution.

One issue I had is that when you pass an object to the template, the property needs to exist or you will get an error. With some object one property was not there, because it was an option. The first attempt to resolve this was to include an conditional in the template but if you wrap the object in a containing object like below then it does work.

This results in an error, because the property icon is not defined.

But if you define it like this:

You can also switch between ERB or use a style like MustacheJS.


MustacheJS Style: (from docs)

When you want to combine both styles, you could create a variable where you store the current settings and revert the _.templateSettings before creating the new template.

Sorting objects on a specific order:

Loops and a call to another template:

Other information worth checking:

A closer look at Underscore templates
View Helpers For Underscore Templates

Leave a Reply

You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">