使用方法
編譯模板並根據數據立即渲染出結果
juicer(tpl, data);
僅編譯模板暫不渲染,返回一個可重用的編譯後的函數
var compiled_tpl = juicer(tpl);
根據給定的數據對之前編譯好的模板進行渲染
var complied_tpl = juicer(tpl); var html = complied_tpl.render(data);
注冊/注銷自定義函數(對象)
juicer.register(‘function_name', function); juicer.unregister(‘function_name');
默認參數配置
{
cache: true [false];
script: true [false];
error handling: true [false];
detection: true [false];
}
修改默認配置,逐條修改
juicer.set('cache', false);
修改默認配置,批量修改
juicer.set({
'script': false,
'cache': false
})
Juicer 默認會對編譯後的模板進行緩存,從而避免同一模板多次數據渲染時候重復編譯所耗的時間, 如無特殊需要,強烈不建議關閉默認參數中的 cache,這麼做將會令 Juicer 緩存失效從而降低性能.
語法
* ${變量}
- 使用${}輸出變量,其中_ 為對數據源的引用(${_})。支持使用自定義函數。
${name}
${name|function}
${name|function, arg1, arg2}
var = links: [{href: 'http://juicer.name', alt: 'Juicer'},
{href: 'http://benben.cc', alt: 'Benben'},
{href: 'http://ued.taobao.com', alt: 'Taobao UED'}
]};
var tpl = [ '{@each links as item}',
'${item|links_build} <br />',
'{@/each}'].join('');
var links = function(data) {
return '<a href="' + data.href + '" alt="' + data.alt + '" />';
};
juicer.register('links_build', links); //注冊自定義函數
juicer(tpl, json);
* 轉義/避免轉義
- ${變量} 在輸出之前會對其內容進行轉義,如果你不想輸出結果被轉義,可以使用 $${變量} 來避免這種情況。
var json = {
value: '<strong>juicer</strong>'
};
var escape_tpl='${value}';
var unescape_tpl='$${value}';
juicer(escape_tpl, json); //輸出 '<strong>juicer</strong>'
juicer(unescape_tpl, json); //輸出 '<strong>juicer</strong>'
*循環遍歷 {@each} ... {@/each}
- 遍歷數組,${index}當前索引
{@each list as item, index}
${item.prop}
${index} //當前索引
{@/each}
*判斷 {@if} ... {@else if} ... {@else} ... {@/if}
*注釋 {# 注釋內容}
{# 這裡是注釋內容}
*輔助循環 {@each i in range(m, n)}
{@each i in range(5, 10)}
${i}; //輸出 5;6;7;8;9;
{@/each}
*子模板嵌套 {@include tpl, data}
- 子模板嵌套除了可以引入在數據中指定的子模板外,也可以通過指定字符串`#id`使用寫在`script`標簽中的模板代碼.
- HTML代碼:
<script type="text/juicer" id="subTpl">
I'm sub content, ${name}
</script>
- Javascript 代碼:
var tpl = 'Hi, {@include "#subTpl", subData}, End.';
juicer(tpl, {
subData: {
name: 'juicer'
}
});
//輸出 Hi, I'm sub content, juicer, End.
//或者通過數據引入子模板,下述代碼也將會有相同的渲染結果:
var tpl = 'Hi, {@include subTpl, subData}, End.';
juicer(tpl, {
subTpl: "I'm sub content, ${name}",
subData: {
name: 'juicer'
}
});
一個完整的例子
HTML 代碼:
<script id="tpl" type="text/template">
<ul>
{@each list as it,index}
<li>${it.name} (index: ${index})</li>
{@/each}
{@each blah as it}
<li>
num: ${it.num} <br />
{@if it.num==3}
{@each it.inner as it2}
${it2.time} <br />
{@/each}
{@/if}
</li>
{@/each}
</ul>
</script>
Javascript 代碼:
var data = {
list: [
{name:' guokai', show: true},
{name:' benben', show: false},
{name:' dierbaby', show: true}
],
blah: [
{num: 1},
{num: 2},
{num: 3, inner:[
{'time': '15:00'},
{'time': '16:00'},
{'time': '17:00'},
{'time': '18:00'}
]},
{num: 4}
]
};
var tpl = document.getElementById('tpl').innerHTML;
var html = juicer(tpl, data);