4

在Django中有一個名爲cycle的模板標籤。 https://docs.djangoproject.com/en/1.3/ref/templates/builtins/#cycle在Handlebars.js中實現循環標籤

一個例子:

{% for o in some_list %} 
    <tr class="{% cycle 'row1' 'row2' %}"> 
     ... 
    </tr> 
{% endfor %} 

輸出:

<tr class="row1">...</tr> 
<tr class="row2">...</tr> 
<tr class="row1">...</tr> 
<tr class="row2">...</tr> 

如何實現在Handlebars.js這種類型的功能?

+0

我不知道這是可能以這種方式擴展Handlebars.js。你打開替代JS模板引擎? – 2012-03-01 23:49:54

+0

無論什麼作品。 – hekevintran 2012-03-02 00:11:50

回答

3

我發現在http://thinkvitamin.com/code/handlebars-js-part-2-partials-and-helpers/

Handlebars.registerHelper("stripes", function(array, even, odd, fn) { 
    if (array && array.length > 0) { 
    var buffer = ""; 
    for (var i = 0, j = array.length; i < j; i++) { 
     var item = array[i]; 

     // we'll just put the appropriate stripe class name onto the item for now 
     item.stripeClass = (i % 2 == 0 ? even : odd); 

     // show the inside of the block 
     buffer += fn(item); 
    } 

    // return the finished buffer 
    return buffer; 
    } 
}); 


{{#stripes myArray "even" "odd"}} 
    <div class="{{stripeClass}}"> 
    ... code for the row ... 
    </div> 
{{/stripes}} 
2

這裏是我想出了:

Handlebars.registerHelper('cycle', function(value, block) { 
    var values = value.split(' '); 
    return values[block.data.index % (values.length + 1)]; 
}); 

{{#each users}} 
    <tr class="{{cycle 'alternate'}}"> 
    <tr class="{{cycle 'odd even'}}"> 
{{/each}} 
+0

我不得不從'(values.length + 1)'中刪除'+ 1',以使其正常工作。它選擇一個空字符串作爲數組末尾的值。 – matueranet 2017-02-07 14:35:03