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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24197046/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 02:20:54  来源:igfitidea点击:

How to write a conditional if statement using underscore template

javascriptunderscore.js

提问by user2942566

I have a Nameand Statusfields on my table and I want to display the values, Active and Inactive for the Status field. Here is the template I'm using:

我的表上有一个NameStatus字段,我想显示状态字段的值,活动和非活动。这是我正在使用的模板:

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

When I run, the template throws:

当我运行时,模板抛出:

Uncaught SyntaxError: Unexpected token 

Why?

为什么?

For reference, below is my accountView.js

作为参考,下面是我的 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}));

                },
            });
        }
    });

回答by Bergi

This doesn't have much to do with underscore templates - it will translate roughly into:

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

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

I'm not sure what you wanted to do here, but this is horribly mixing the if statementwith the conditional operatorsyntax. Use either

我不确定你想在这里做什么,但这是将if 语句条件运算符语法可怕地混合在一起。使用任一

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

or

或者

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