artTemplate语法(转)
编写模板
使用一个type="text/html"的script标签存放模板:
<script id="test" type="text/html">
<h1>{{title}}</h1>
<ul>
{{each list as value i}}
<li>索引 {{i + 1}} :{{value}}</li>
{{/each}}
</ul>
</script>
渲染模板
var data = {
title: '标签',
list: ['文艺', '博客', '摄影', '电影', '民谣', '旅行', '吉他']
};
var html = template('test', data);
document.getElementById('content').innerHTML = html;
模板语法
有两个版本的模板语法可以选择。
简洁语法
推荐使用,语法简单实用,利于读写。
{{if admin}}
{{include 'admin_content'}}
{{each list}}
<div>{{$index}}. {{$value.user}}</div>
{{/each}}
{{/if}}
原生语法
<%if (admin){%>
<%include('admin_content')%>
<%for (var i=0;i<list.length;i++) {%>
<div><%=i%>. <%=list[i].user%></div>
<%}%>
<%}%>
下载
- template.js (简洁语法版, 2.7kb)
- template-native.js (原生语法版, 2.3kb)
方法
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 多余空白字符 |
使用预编译
可突破浏览器限制,让前端模板拥有后端模板一样的同步“文件”加载能力:
一、按文件与目录组织模板
template('tpl/home/main', data)
二、模板支持引入子模板
{{include '../public/header'}}
基于预编译:
- 可将模板转换成为非常精简的 js 文件(不依赖引擎)
- 使用同步模板加载接口
- 支持多种 js 模块输出:AMD、CMD、CommonJS
- 支持作为 GruntJS 插件构建
- 前端模板可共享给 NodeJS 执行
- 自动压缩打包模板
预编译工具:TmodJS
NodeJS
安装
npm install art-template
使用
var template = require('art-template');
var data = {list: ["aui", "test"]};
var html = template(__dirname + '/index/main', data);
配置
NodeJS 版本新增了如下默认配置:
| 字段 | 类型 | 默认值 | 说明 |
|---|---|---|---|
| base | String | '' |
指定模板目录 |
| extname | String | '.html' |
指定模板后缀名 |
| encoding | String | 'utf-8' |
指定模板编码 |
配置base指定模板目录可以缩短模板的路径,并且能够避免include语句越级访问任意路径引发安全隐患,例如:
template.config('base', __dirname);
var html = template('index/main', data)
NodeJS + Express
var template = require('art-template');
template.config('base', '');
template.config('extname', '.html');
app.engine('.html', template.__express);
app.set('view engine', 'html');
//app.set('views', __dirname + '/views');
运行 demo:
node demo/node-template-express.js
若使用 js 原生语法作为模板语法,请改用
require('art-template/node/template-native.js')
升级参考
为了适配 NodeJS express,artTemplate v3.0.0 接口有调整。
接口变更
- 默认使用简洁语法
template.render()方法的第一个参数不再是 id,而是模板字符串- 使用新的配置接口
template.config()并且字段名有修改 template.compile()方法不支持 id 参数- helper 方法不再强制原文输出,是否编码取决于模板语句
template.helpers中的$string、$escape、$each已迁移到template.utils中template()方法不支持传入模板直接编译
升级方法
- 如果想继续使用 js 原生语法作为模板语言,请使用 template-native.js
- 查找项目
template.render替换为template - 使用
template.config(name, value)来替换以前的配置 template()方法直接传入的模板改用template.compile()(v2初期版本)
转自:https://github.com/aui/artTemplate
浙公网安备 33010602011771号