【问题标题】:Underscore.js template compilation [duplicate]Underscore.js 模板编译
【发布时间】:2014-10-22 08:49:45
【问题描述】:

基本上我想要做的是使用下划线 js 编译带有一些数据的模板。我的代码如下:

var temp = "<div> Hello <%=names%> </div>";
var html = _.template(temp, {names:'world'};

我希望我的变量 html 是

<div> Hello world </div> 

但由于某种原因,变量名称未定义,而编译和模板从不编译。

这是最基本的下划线 js,根据documentation 和网络上的许多示例,它应该可以工作。我做错了什么?

【问题讨论】:

    标签: javascript underscore.js frontend underscore.js-templating


    【解决方案1】:

    _.template function 发生了一些变化,假设您使用的是最新版本,它现在会生成一个函数,而不是编译后的 HTML,您必须使用要显示的数据调用该函数。

    var temp = "<div> Hello <%= names %> </div>";
    var html = _.template(temp);
    console.log(html({names:'world'}));
    
    "<div> Hello world </div>"
    

    【讨论】:

    • 你刚刚救了我的命...
    • 没问题,黑客愉快! :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多