2012-02-01 58 views
1

所以我想<如果值是數組,否則只顯示值。 我想我可以寫一個函數來做到這一點,但想知道是否有更好的方式來做到這一點與jQuery模板?jQuery的模板值是數組或字符串 - 如何處理

<script id="template" type="x-jquery-tmpl"> <table> 
    <tr> 
    <td>${name}</td> 
    <td>{{each value}}${$value}<br/>{{/each}}</td> 
    </tr> </table> 
</script> 

<script> 
     var data = [ 
        { 
         name: "blah", 
         value: ["1", "2", "3"] 
        }, 
        { 
         name: "blah blah", 
         value : "abc" 
        } 
       ]; 

$('#template').tmpl(data).appendTo('#target); 
    </script> 

<div id="target"> 

</div> 

回答

3

像這樣的東西應該工作:

<script id="template" type="x-jquery-tmpl"> <table> 
    <tr> 
    <td>${name}</td> 
    {{if typeof value == 'array'}} 
     <td>{{each value}}${$value}<br/>{{/each}}</td> 
    {{/if}} 
    {{else}} 
     <td>${value}<br/></td> 
    {{/else}} 
    </tr> </table> 
</script> 
相關問題