避免重复使用下划线模板 - 骨干

Ale*_*and 1 javascript backbone.js underscore.js

假设我有一个具有一堆布尔属性的主干模型:

Car = Backbone.Model.extend({});

car_one = new Car({
    a_c: true,
    mp3: true,
    gps: false,
    touchscreen: false,
    // etc...
})
Run Code Online (Sandbox Code Playgroud)

我希望能够呈现这些布尔属性的列表,并在它们旁边有一个图标,具体取决于true或false.如果为true,则图标将为绿色勾号,否则显示红色X图标.

有些东西:

<ul>
<li><img src="tick.png">AC</li>
<li><img src="tick.png">MP3</li>
<li><img src="cross.png">Gps</li>
<li><img src="cross.png">Touch screen</li>
</ul>
Run Code Online (Sandbox Code Playgroud)

有没有更好的方式来做到这一点,而不是每个包裹li在一个if statement模板:

<% if (model.a_c === true) { %>
    // show tick...
<% } else { %>
   // show red cross..
<% } %>
Run Code Online (Sandbox Code Playgroud)

我有大约12个布尔属性需要像这样渲染...

mu *_*ort 5

您可以从模板中访问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;
    }
};
Run Code Online (Sandbox Code Playgroud)

然后你会想要利用以下variable选项_.template:

默认情况下,模板通过with语句将数据中的值放在本地作用域中.但是,您可以使用变量设置指定单个变量名称.这可以显着提高模板能够呈现的速度.

   _.template("<%= data.hasWith %>", {hasWith: 'no'}, {variable: 'data'});
   => "no"
Run Code Online (Sandbox Code Playgroud)

然后你可以在你的模板中有这样的东西:

<%= underscore_helpers.list_of_booleans(
    json,
    ['a_c', 'mp3', 'gps', 'touchscreen']
) %>
Run Code Online (Sandbox Code Playgroud)

并使用这样的模板:

var html = _.template($('#t').html(), model.toJSON(), { variable: 'json' });
// or
var tmpl = _.template($('#t').html(), null, { variable: 'json' });
var html = tmpl(model.toJSON());
Run Code Online (Sandbox Code Playgroud)

演示:http://jsfiddle.net/ambiguous/Yr4m5/

通过使用该variable选项,你不得不说<%= json.attribute %>,<%= attribute %>但这是非常小的.

您可以使用类似的方法<li>逐个格式化s并在模板中保留更多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>????????????????????
Run Code Online (Sandbox Code Playgroud)

演示:http://jsfiddle.net/ambiguous/983ks/

您会注意到这也使用了该variable: 'json'选项,您需要这样做,以便[]当名称在变量中时,您可以使用on来按名称获取字段.这个