我继承了这样的Underscore模板:
<script type="text/template" id="tpl-post">
<div class="ti-author-box">
<% _.each(authors, function(author) { %>
<% if ( author.author_image ) { %>
<img class="ti-author-image" src="<%= author.author_image %>" alt="<%= author.author_display_name %>" />
<% } else { %>
<img class="ti-author-image" src="<?php bloginfo('template_directory'); ?>/img/default-user.png?resize=40%2C40" alt="<%= author.author_display_name %>" />
<% } %>
<div class="ti-author-name" ><%= author.author_display_name %></div>
<% }); %>
</div>
...
</script>
authors
是一个作者数组,每个元素都是一个具有author_image
和author_display_name
等属性的对象。
我的问题是,我怎样才能将其更改为仅显示数组中第一个作者的信息,而不是使用_.each()循环遍历数组?
答案 0 :(得分:0)
你不能只添加0数组索引,如:
<% if ( author[0].author_image ) { %>
<img class="ti-author-image" src="<%= author[0].author_image %>" alt="<%= author[0].author_display_name %>" />
<% } else { %>
<img class="ti-author-image" src="<?php bloginfo('template_directory'); ?>/img/default-user.png?resize=40%2C40" alt="<%= author[0].author_display_name %>" />
<% } %>
<div class="ti-author-name" ><%= author[0].author_display_name %></div>
答案 1 :(得分:-2)
你应该只能选择数组的第一个元素。
<script type="text/template" id="tpl-post">
<div class="ti-author-box">
<% var author = authors[0]; %>
<% if ( author.author_image ) { %>
<img class="ti-author-image" src="<%= author.author_image %>" alt="<%= author.author_display_name %>" />
<% } else { %>
<img class="ti-author-image" src="<?php bloginfo('template_directory'); ?>/img/default-user.png?resize=40%2C40" alt="<%= author.author_display_name %>" />
<% } %>
<div class="ti-author-name" ><%= author.author_display_name %></div>
</div>
...
</script>