倘若我们把数据比作新鲜可口的水果,把模板看做是水,Juicer 就是把水果和水榨出我们需要的HTML代码片段的榨汁机。
<script type="text/javascript" src="juicer-min.js"></script>
编译模板并根据所给的数据立即渲染出结果.
juicer(tpl, data);
$变量} 使用
{_},常用于数据源为数组的情况)。支持自定义函数(通过自定义函数你可以实现很多有趣的功能,类似 ${datalinks就可以通过事先定义的自定义函数 links 直接对 data 拼装出 ).
${name}
${name|function}
${name|function, arg1, arg2}
让我们通过一个例子演示一下自定义函数的奇妙用法吧.
var json = {
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);
上述代码执行后我们会发现结果是这样的:
<a href="http://juicer.name" alt="Juicer" <br />
<a href="http://benben.cc" alt="Benben" <br />
<a href="http://ued.taobao.com" alt="Taobao UED" <br />
出于安全角度的考虑,
${变量} 来避免这种情况。例如:
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 list as item}
${item.prop}
{@/each}
如果遍历过程中想取得当前的索引值,也很方便.
{@each list as item, index}
${item.prop}
${index} //当前索引
{@/each}
{@each list as item,index}
{@if index===3}
the index is 3, the value is ${item.prop}
{@else if index === 4}
the index is 4, the value is ${item.prop}
{@else}
the index is not 3, the value is ${item.prop}
{@/if}
{@/each}