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>'
b. 循环遍历 {@each} ... {@/each}
如果你需要对数组进行循环遍历的操作,就可以像这样使用 each .
{@each list as item}
${item.prop}
{@/each}
如果遍历过程中想取得当前的索引值,也很方便.
{@each list as item, index}
${item.prop}
${index} //当前索引
{@/each}
c. 判断 {@if} ... {@else if} ... {@else} ... {@/if}
我们也会经常碰到对数据进行逻辑判断的时候.
{@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}
d. 注释 {# 注释内容}
为了后续代码的可维护性和可读性,我们可以在模板中增加注释.
{# 这里是注释内容}
e. 辅助循环 {@each i in range(m, n)}
辅助循环是 Juicer 为你精心设置的一个语法糖,也许你会在某种情境下需要它.
{@each i in range(5, 10)}
${i}; //输出 5;6;7;8;9;
{@/each}
var juicerExpressAdapter = require('juicer-express-adapter');
app.set('view engine', 'html');
app.engine('html', juicerExpressAdapter);
在命令行预编译模板文件:
npm install -g juicer
juicer example.juicer.tmpl -f example.js
// type `juicer` after install for more help.
// 全局模式安装 `juicer` 后,在命令行下输入 `juicer` 可以获得更多帮助信息。
为模板引擎设置外部Cache存储:
var juicer = require('juicer');
var LRUCache = require('lru-native');
var cache = new LRUCache({ maxElements: 1000 });
juicer.set('cachestore', cache);
* 一个完整的例子
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);
请发表评论