2012-06-24 62 views
1

假設我有一個有一堆布爾屬性的骨幹機型:有下劃線的模板避免重複 - 骨幹

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> 

有沒有更好的方式來做到這一點,而不是在模板中的if statement包裹每個li

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

我有大約12布爾屬性需要像這樣呈現...

回答

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; 
    } 
}; 

那麼你要採取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

+0

好東西,我一定會看看這個 – AlexBrand