Hogan.js浏览器端编译
Hogan.js 是 Mustache 模板引擎的另一套实现,增加了预编译机制,使得模板字符串可以在打包阶段被预先处理成模板函数,这样浏览器就不必再重复去编译模板。
Hogan.js 同时提供了可以运行与_浏览器端,浏览器端负责用预编译后的代码渲染页面。
var Template = {
_cache: {},
// 所有的模板放在这个对象下
_template: {
hello: /*TMPL*/"hello {{name}}!"/*TMPL*/
},
// 这个适配函数会同时处理字符串模板和模板函数的情况
render: function (name, data) {
if (!this._cache[name]) {
// 如果代码被预编译过,则不需要 compile
if (typeof this._template[name] === 'function') {
this._cache[name] = new Hogan.Template(this._template[name]);
} else if (typeof this._template[name] === 'string') {
this._cache[name] = Hogan.compile(this._template[name]);
}
}
return this._cache[name].render(data);
}
};
console.log(Template.render('hello', {name: "hubwiz"})); // hello hubwiz!
console.log(Template.render('hello', {name: "汇智网"})); // hello 汇智网!