Search code examples
javascripthtmlunderscore.jsunderscore.js-templating

Conditional template based on data in underscore.js


I am using underscore.js html template to render html for the following json (simplified):

[
 {
   "$id": "1",
   "Type": 3000,
   "Date": "2014-02-26T07:17:03+05:00"
 },
 {
   "$id": "1",
   "Type": 2000,
   "Date": "2014-02-26T07:17:03+05:00"
 },

]

I have to render Html for each item in the array based on the Type field. The html for each Type is quite different and my current template is littered with html and if else conditions , pretty much like this:

<script type="text/template" class="template">
   <% _.each(streams, function(data) { if(data.Type == 3000){ %>
   // Some long html here for type 3000

   <% if(data.Type == 2000){%>
   // html for type 2000
   <% }}}); %>
</script>

How can I avoid writing if else conditions in the template and possibly create a template for each `type' so I can easily maintain my templates.


Solution

  • It can be done by calling templates inside the template like:

    <script type="text/template" class="template">
        <div>
          <% _.each(data, function(child) { %>
              <%= _.template($('.template_'+child.Type).html())(child) %>
          <% }); %>
        </div>
    </script>
    
    <script type="text/template" class="template_3000">
        <div>
          3000 Template
        </div>
    </script>
    
    <script type="text/template" class="template_2000">
        <div>
          2000 Template
        </div>
    </script>
    

    See http://jsfiddle.net/L2b9H/ for working example.