underscore.js预编译模板使用

时间:2013-09-12 04:16:48

标签: underscore.js template-engine precompile underscore.js-templating

我想使用预编译的underscore.js模板。我使用_.template().source并将结果保存在文件中。但我不明白,如何使用这个模板。预编译模板是字符串,我无法将其强制转换为函数。我尝试使用eval,但它总是返回解析错误。

例如:

<div>
    <% for(var i = 0; i < 5; i++){ %>
        <div><%=i%></div>
    <% } %>
</div>

标准使用:

_.template(tpl).({});

结果:

<div>

    <div>0</div>

    <div>1</div>

    <div>2</div>

    <div>3</div>

    <div>4</div>

</div>

预编译:

_.template(tpl).source

预编译模板:

"function(obj){
var __t,__p='',__j=Array.prototype.join,print=function(){__p+=__j.call(arguments,'');};
with(obj||{}){
__p+='<div>\n\t';
 for(var i = 0; i < 5; i++){ 
__p+='\n\t\t<div>'+
((__t=(i))==null?'':__t)+
'</div>\n\t';
 } 
__p+='\n</div>\n';
}
return __p;
}"

运行预编译模板:

var a = eval(tplc);
a({});

错误:

Error
line: 1
message: "Parse error"
sourceId: 139746789246216
__proto__: SyntaxError

2 个答案:

答案 0 :(得分:1)

是的,source属性将编译后的模板作为字符串返回。您可以将该字符串写入定义JavaScript对象文字的文件,如下所示:

window.JST = { };
JST.some_name = function(obj){ ... };
// The rest of the compiled template functions go here

然后,将其加载到浏览器中,就像任何其他JavaScript文件一样,您最终会在JST中找到一堆已编译的模板函数:

var html = JST.some_name(data);

您可以根据需要构建JST定义,这只是一种简单的方式来说明整体方法。

请记住,字符串是否只是一些文本要像任何其他文本一样被操纵(例如将其写入文件),或者它是否是JavaScript源代码取决于谁在解释字符串。

答案 1 :(得分:-2)

我终于找到了this解决方案。我不能说这是优雅的解决方案,但它的确有效。 对于我的例子:

var a = eval('[' + tplc + ']')[0];
a({});
相关问题