Handlebars模板引擎渲染頁面
阿新 • • 發佈:2017-08-16
再次 模板引擎 單列 this pen 數據 roi and array
基本使用,並簡單列舉了幾種常見的數據格式的渲染方式
js: var testTpl = Handlebars.compile($(‘#test‘).html()); //模板 var arr = [1,2,3] //數據 $(‘#box‘).append(testTpl(arr)); //調用
html: <script type="text/x-handlebars-template" id="test"> {{#each this}} <li>索引:[email protected]}},內容:{{this}}</li> {{/each}} </script>
下面說幾種數據源如何渲染數據,js中基本一樣,聲明模板->聲明要渲染數據->調用並插入到頁面 ,不明白看 上面基本使用
數據源是Array
js: var arr = [1,2,3] html: {{#each this}} <li>索引:[email protected]}},內容:{{this}}</li> {{/each}}
數據源是數組對象(對象內部包含數組,再次each這個數組即可)
js: var arr = [ {‘a‘:‘1‘,‘b‘:2,‘c‘:[‘4‘,‘5‘,‘6‘]}, {‘a‘:‘11‘,‘b‘:22,‘c‘:[‘44‘,‘55‘,‘66‘]} ]; html:{{#each this}} <li>{{a}}</li> <li>{{b}}</li> {{#each c}} <li>父級索引{{..[email protected]}}:訪問父級:{{../a}} 。當前索引:[email protected]}},當前元素:{{this}} </li> {{/each}} {{/each}}
數據源是對象
js: var context = { data:{ one: "un", two:"deux", three: "trois" } } html: <ul> {{#each data}} <li>對象的key:[email protected]}},對象的值:{{this}}</li> {{/each}} </ul> <ol> {{#each data}} <li>對象的索引:[email protected]}},對象的值:{{this}}</li> {{/each}} </ol>
數據源數對象數組
js: var context = { data: ["one", "two", "three"], data2: ["one", "two", "three"], }; html: <ul> {{#each data}} <li> 數組的索引:[email protected]}} ,索引對應的內容:{{this}}{{#eq @index 0}}王生輝{{/eq}} </li> {{/each}} {{#each data2}} <li> 數組的索引:[email protected]}},索引對應的內容:{{shenghui this}} </li> {{/each}} </ul>
說明:@key [email protected]
@key:如果當循環的數據是數組 則返回下標,如果是對象則返回key值
[email protected]:都返回下標
Handlebars模板引擎渲染頁面