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

Avoiding repetition with underscore templates - backbone

本文关键字:骨干 下划线      更新时间:2023-09-26

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

Car = Backbone.Model.extend({});
car_one = new Car({
    a_c: true,
    mp3: true,
    gps: false,
    touchscreen: false,
    // etc...
})

我希望能够呈现这些布尔属性的列表,并在它们旁边有一个图标,具体取决于真或假。如果为 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>

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

<% if (model.a_c === true) { %>
    // show tick...
<% } else { %>
   // show red cross..
<% } %>

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

您可以从模板中访问 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选项来_.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' 选项,您需要它,以便当名称位于变量中时,您可以使用 [] 按名称获取字段。这个