如何使用下划线模板编写条件if语句

use*_*566 0 javascript underscore.js

我在桌面上有一个NameStatus字段,我想显示Status字段的值Active和Inactive.这是我正在使用的模板:

  <tbody>
<% _.each(accountLists, function(account) { if (account.active == 'true') ? 'Active': 'Inactive'%>
        <tr>
            <td><%= account.active %></td>
        </tr>
    <% }) %>
</tbody>
Run Code Online (Sandbox Code Playgroud)

当我运行时,模板抛出:

Uncaught SyntaxError: Unexpected token 
Run Code Online (Sandbox Code Playgroud)

为什么?

作为参考,下面是我的accountView.js

var AccountList = Backbone.View.extend({

        initialize: function(){

},

    el:'#sub-account-list', 
    render: function(id){

    var self = this;
        var accountList = new SubAccountCollection([],{ id: id });

        accountList.fetch({
        success: function(accountLists){

            var data = accountLists.toJSON();
            var accounts = data[0].data.items;
            var template = $("#sub-account-list").html(_.template(tmpl, {accounts:accounts}));

                },
            });
        }
    });
Run Code Online (Sandbox Code Playgroud)

Ber*_*rgi 5

这与下划线模板没有太大关系 - 它将大致转换为:

_.each(accountLists, function(account) {
    if (account.active == 'true') ? 'Active': 'Inactive'
    echo ("<tr><td>" + account.active "</td></tr>");
})
Run Code Online (Sandbox Code Playgroud)

我不确定你想在这里做什么,但这很可能将if语句条件运算符语法混合在一起.使用其中之一

<tbody>
    <% _.each(accountLists, function(account) {
        if (account.active == 'true') { %>
        <tr>
            <td>Active</td>
        </tr>
    <%  } else { %>
        <tr>
            <td>Inactive</td>
        </tr>
    <%  }
    }); %>
</tbody>
Run Code Online (Sandbox Code Playgroud)

要么

<tbody>
    <% _.each(accountLists, function(account) { %>
        <tr>
            <td><%= (account.active == 'true') ? 'Active': 'Inactive' %></td>
        </tr>
    <% }); %>
</tbody>
Run Code Online (Sandbox Code Playgroud)