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
How to write a conditional if statement using underscore template
提问by user2942566
I have a Name
and Status
fields on my table and I want to display the values, Active and Inactive for the Status field. Here is the template I'm using:
我的表上有一个Name
和Status
字段,我想显示状态字段的值,活动和非活动。这是我正在使用的模板:
<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>