I am using underscore.js's templating library, and I am not sure how to go about using a logic inside of a template. for example, I would like to print an array of tags in a template. What is the best approach for this?
Javascript:
bunny_data = {
name: "sprinkles",
age: 1,
tags: ['fuzzy','wuzzy']
};
bunny_view = $("#bunny-template").html();
$(body).append(_.template(bunny_view,bunny_data));
Template:
<script type='text/template'>
<div>
<h5><% = name %></h5>
<ul class='tag-list'>
<!-- How do I print the tags here? -->
</ul>
</div>
</script>
You don't need to encapsulate bunny_data
as @Ken suggests, you were on the right track. Whether or not you want to call _.
functions or just use plain Javascript constructs is up to you, but there's no built-in flow constructs in Underscore templates, to do that you just embed code (you might want to look into eco or Mustache or something if you want that).
My example looks like this (almost the same as you own):
<script type='text/template' id="bunny-template">
<div>
<h5><%= name %></h5>
<ul>
<% for(var tag in tags) { %>
<li><%= tags[tag] %></li>
<% } %>
</ul>
</div>
</script>
with the following Javascript:
bunny_data = {
name: "sprinkles",
age: 1,
tags: ['fuzzy','wuzzy']
};
bunny_view = $("#bunny-template").html();
$(body).append(_.template(bunny_view, bunny_data));
You can verify that it runs here.
(On a personal preference note, I'm a heavy user of all of Underscore except the templates for this reason, I'm not comfortable with the amount of code you must put in them if you have a more complicated use case).
It looks like you are not setting bunny_data
properly in your JavaScript.
Instead of:
$(body).append(_.template(bunny_view,bunny_data));
Try:
$(body).append(_.template(bunny_view, { bunny_data: bunny_data }));
Print the data in your template (notice I removed the space after % in <%= name %>
):
<script type='text/template'>
<div>
<h5><%= name %></h5>
<ul class='tag-list'>
<% _.each(bunny_data, function(bd) { %>
<li><%= bd.name %></li>
...
<% }); %>
</ul>
</div>
</script>
Hopefully that helps.
Also join
will do the trick, so in html you'll have
<ul>
<li><%= tags.join('</li><li>') %></li>
</ul>
Check it at jsFiddle.