Search code examples
jquerytemplatesunderscore.jsunderscore.js-templating

Underscore.js template loop from object iteration


I have the following template for a modal

<div class="ui-modal">
  <div class="mask"></div> 
  <div class="ui-modal-container">
    <div class="ui-modal-header">
      <h3><%= modal['title'] %></h3>
    </div>
    <div class="ui-modal-text">
      <p><%= modal['description'] %></p>
    </div>
    <% if ( modal['buttons'] !== 'undefined' ) { %>
      <div class="ui-button-container">
        <a class="ui-button ui-button-pill <%= modal['buttons'][0]['extra_class'] %> " href="<%= modal['buttons'][0]['href'] %>">
          <span class="label">
            <span class="section"><%= modal['buttons'][0]['label'] %></span> 
          </span>
        </a>
      </div>
    <% } %>
  </div>
</div>

and this is the data I am trying to populate it with:

_data = {
 "modal" : {
    "title" : "Your address is:",
    "description" : "Some desc here",
    "buttons" : [
       {'extra_class': 'small left', 'href' : '#register/3', 'label' : 'Back'},
       {'extra_class': 'small center', 'href' : '#register/4',  'label' : 'Next'},
       {'extra_class': 'small right', 'href' : '#', 'label' : 'Reset'}
     ]
   }
 }

What I want to achieve is an iteretaion where I had "hardcoded" the index (0) in <%= modal['buttons'][0]['extra_class'] %>. I presume this is an easy question, but unfortunately I could find anything that I could apply in my case.

Any help will be greatly appreciated!

Thank you!


Solution

  • The stuff inside <% ... %> in an Underscore template is just JavaScript. That means that you can iterate over arrays the same way you would anywhere else: for-loops, _.each, forEach, ...

    A typical Underscore-ish way would be:

    <% if(modal['buttons']) { %>
      <div class="ui-button-container">
        <% _(model['buttons']).each(function(button) { %>
          <a class="ui-button ui-button-pill <%= button.extra_class %> " href="<%= button.href %>">
            <span class="label">
              <span class="section"><%= button.label %></span> 
            </span>
          </a>
        <% }) %>
      </div>
    <% } %>
    

    You could also use a simple for-loop:

    <% if(modal['buttons']) { %>
      <div class="ui-button-container">
        <% for(var i = 0; i < model.buttons.length; ++i) { %>
          <a class="ui-button ui-button-pill <%= model.buttons[i].extra_class %> " href="<%= model.buttons[i].href %>">
            <span class="label">
              <span class="section"><%= model.buttons[i].label %></span> 
            </span>
          </a>
        <% } %>
      </div>
    <% } %>