最简单模板
html标签:
{{title}}
- {{each list as value i}}
- 索引 {{i + 1}} :{{value}}
- {{/each}}
JS代码:
var data = {
title: ‘标签’,
list: [‘文艺’, ‘博客’, ‘摄影’, ‘电影’, ‘民谣’, ‘旅行’, ‘吉他’]
};
var html = template(‘test’, data);
document.getElementById(‘content’).innerHTML = html;
模板语法
简洁语法
推荐使用,语法简单实用,利于读写。
引用简洁语法的引擎版本,例如:
示例: {{if admin}} {{include ‘admin_content’}} {{each list}}admin
{{else if code > 0}}master
{{else}}error!
{{/if}} #### 遍历表达式 无论数组或者对象都可以用 each 进行遍历。 {{each list as value index}}- {{index}} - {{value.user}}
- {{/each}} 亦可以被简写: {{each list}}
- {{index}} - {{value.user}}
- {{/each}} #### 模板包含表达式 用于嵌入子模板。 {{include ‘template_name’}} 子模板默认共享当前数据,亦可以指定数据: {{include ‘template_name’ news_list}} 示例:
{{title}}
{{include 'list'}}- {{each list as value i}}
- 索引 {{i + 1}} :{{value}}
- {{/each}}
辅助方法
使用template.helper(name, callback)注册公用辅助方法:
template.helper(‘dateFormat’, function (date, format) {
// ..
return value;
});
模板中使用的方式:{{time | dateFormat:’yyyy-MM-dd hh:mm:ss’}}
支持传入参数与嵌套使用:{{time | say:’cd’ | ubb | link}}
在javascript中存放模板
var source = ‘
-
’
+ ‘{{each list as value i}}’
+ ‘ - 索引 {{i + 1}} :{{value}}
- ’
+ ‘{{/each}}’
+ ‘
var render = template.compile(source);
var html = render({
list: [‘摄影’, ‘电影’, ‘民谣’, ‘旅行’, ‘吉他’]
});document.getElementById(‘content’).innerHTML = html;
print方法
print
{{print a b c}} var html = ''; var data = { a: 'hello', b: '--world', c: '--!!!' }; html = template('test', data); document.write(html);原生语法
template方法
template(id, data)
根据 id 渲染模板。内部会根据document.getElementById(id)查找模板。
如果没有 data 参数,那么将返回一渲染函数。
template.compile(source, options)
将返回一个渲染函数。演示
template.render(source, options)
将返回渲染结果。
template.helper(name, callback)
添加辅助方法。
例如时间格式器:演示
template.config(name, value)
更改引擎的默认配置。
字段 类型 默认值 说明
openTag String ‘{{’ 逻辑语法开始标签
closeTag String “}}” 逻辑语法结束标签
escape Boolean true 是否编码输出 HTML 字符
cache Boolean true 是否开启缓存(依赖 options 的 filename 字段)
compress Boolean false 是否压缩 HTML 多余空白字符