下划线模板 - 显示数组中的第一项

时间:2013-11-29 10:18:35

标签: javascript underscore.js

我继承了这样的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_imageauthor_display_name等属性的对象。

我的问题是,我怎样才能将其更改为仅显示数组中第一个作者的信息,而不是使用_.each()循环遍历数组?

2 个答案:

答案 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>