您可以从模板中访问JavaScript函数。所以,你可以把东西window
(即全球范围):
window.underscore_helpers = {
list_of_booleans: function(obj, bools) {
// 'obj' is the object for the template, 'bools'
// is an array of field names. Loop through 'bools'
// and build your HTML...
return the_html_li_elements;
}
};
那么你要采取variable
option to _.template
的优势:
默认情况下,模板从地方值的本地范围内的数据通过with
声明。但是,您可以使用变量设置来指定单个变量名称。这可以显着提高模板能够呈现的速度。
_.template("<%= data.hasWith %>", {hasWith: 'no'}, {variable: 'data'});
=> "no"
然后你就可以有这样的事情在你的模板:
<%= underscore_helpers.list_of_booleans(
json,
['a_c', 'mp3', 'gps', 'touchscreen']
) %>
,并使用你的模板是这样的:
var html = _.template($('#t').html(), model.toJSON(), { variable: 'json' });
// or
var tmpl = _.template($('#t').html(), null, { variable: 'json' });
var html = tmpl(model.toJSON());
演示:http://jsfiddle.net/ambiguous/Yr4m5/
通过使用variable
选项你不得不说<%= json.attribute %>
而不是<%= attribute %>
,但这很小。
您可以使用类似的方法逐个格式化<li>
,并在模板中保留更多HTML。
另一种选择是抛出一个for
循环到模板中,这样的事情:
<script id="t" type="text/x-underscore-template">
<ul>
<% var fields = ['a_c', 'mp3', 'gps', 'touchscreen' ] %>
<% for(var i = 0; i < fields.length; ++i) { %>
<li class="<%= json[fields[i]] ? 'true' : 'false' %>"><%= fields[i] %></li>
<% } %>
</ul>
</script>
演示:http://jsfiddle.net/ambiguous/983ks/
你会发现,这里使用了variable: 'json'
选项,以及,你需要一个所以当名字在变量中时,你可以使用[]
来按名称获取字段。 This al
好东西,我一定会看看这个 – AlexBrand