swig
swig 介绍
swig是js模板引擎,它有如下特点:
支持大多数主流浏览器。
表达式兼容性好。
面向对象的模板继承。
将过滤器和转换应用到模板中的输出。
可根据路劲渲染页面。
支持页面复用。
支持动态页面。
可扩展、可定制。
1、API
swig.init({
allowErrors: false,
autoescape: true,
cache: true,
encoding: 'utf8',
filters: {},
root: '/',
tags: {},
extensions: {},
tzOffset: 0
});
options:
allowErrors: 默认值为 false。将所有模板解析和编译错误直接输出到模板。如果为 true,则将引发错误,抛出到 Node.js 进程中,可能会使您的应用程序崩溃。
autoescape: 默认true,强烈建议保持。字符转换表请参阅转义过滤器。
true: html安全转义
false: 不转义,除非使用转义过滤器或者转义标签
'js': js安全转义
cache: 更改为 false 将重新编译每个请求的模板的文件。正式环境建议保持true。
encoding: 模板文件编码
root: 需要搜索模板的目录。如果模板传递给 swig.compileFile 绝对路径(以/开头),Swig不会在模板root中搜索。如果传递一个数组,使用第一个匹配成功的数组项。
tzOffset: 设置默认时区偏移量。此设置会使转换日期过滤器会自动的修正相应时区偏移量。
filters:自定义过滤器或者重写默认过滤器,参见自定义过滤器指南。
tags: 自定义标签或者重写默认标签,参见自定义标签指南。
extensions: 添加第三方库,可以在编译模板时使用,参见参见自定义标签指南。
2、nodejs
var tpl = swig.compileFile("path/to/template/file.html");var renderedhtml = tpl.render({ vars: 'to be inserted in template' });或者var tpl = swig.compile("Template string here");var renderedhtml = tpl({ vars: 'to be inserted in template' });3、结合Express
npm install expressnpm install consolidate然后app.engine('.html',cons.swig);app.set('view engine','html');4、浏览器
Swig浏览器版本的api基本与nodejs版相同,不同点如下:
不能使用swig.compileFile,浏览器没有文件系统
你必须提前使用swig.compile编译好模板
按顺序使用extends,import,and include,同时在swig.compile里使用参数templateKey来查找模板
var template = swig.compile('<p>{% block content %}{% endblock %}</p>',{ filename: 'main' });
var mypage = swig.compile('{% extends "main" %}{% block content %}Oh hey there!{% endblock %}',{ filename: 'mypage' });
GitHub:https://github.com/paularmstrong/swig
网站描述:nodejs前端模板引擎