Underscore.js模板循环来自对象迭代。

3
我有一个用于模态框的以下模板。
<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>

这是我正在尝试填充的数据:
_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'}
     ]
   }
 }

我想要实现的是一次迭代,我在<%= modal['buttons'][0]['extra_class'] %>中“硬编码”了索引(0)。我认为这是一个简单的问题,但不幸的是,我找不到适用于我的情况的任何东西。
非常感谢您的帮助!
谢谢!
1个回答

12
<% ... %> 标签中的内容实际上是 JavaScript 代码。这意味着您可以像其他任何地方一样迭代数组:使用 for 循环、_.eachforEach 等。

典型的 Underscore 风格可能如下:

<% 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>
<% } %>

你也可以使用一个简单的 for 循环:

<% 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>
<% } %>

非常感谢您的帮助!这正是我所需要的! :) - Chris Panayotova

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接