Underscore.js模板渲染

11

我有这个示例代码,用underscore模板渲染简单的未转义HTML。

var template = $(this.el).html(_.template(this.template, {'data': '<script>'}));
$(this.parent).append(template);

但是当我尝试渲染它时,却出现了错误:

Uncaught TypeError: 对象[object Object]没有方法'replace'

请问有人可以告诉我这是什么原因以及如何解决吗? 因为在underscore的文档中:

var template = _.template("<b>&lt;%- value %></b>");
template({value : '&lt;script&gt;'});
=> "<b>&lt;script&gt;</b>"

提前感谢。


1
this.template是什么?是一个字符串,还是一个DOM或jQuery对象? - mu is too short
是的,这是jQuery对象。另外,当我尝试使用underscore文档中的示例时,它也会抛出错误:“value”未定义,尽管我已将其用字符串括起来。 - fadzril
2个回答

26

根据精细手册:

template _.template(templateString, [context])

将JavaScript模板编译为可评估的函数以进行渲染。

_.template的第一个参数应该是一个字符串,而不是jQuery对象。对于_.template的部分内部处理调用了String#replace函数,这也是你出错的原因。你可能想使用这个代替:

var template = $(this.el).html(_.template(this.template.html(), {'data': '<script>'}));
$(this.parent).append(template);

演示:http://jsfiddle.net/ambiguous/wPu6G/

你提供的示例可以正常工作:

http://jsfiddle.net/ambiguous/w2qWe/

所以我不知道你在评论中提到的“value未定义”的错误可能来自哪里。


1
我在服务器上运行node时遇到了相同的错误。如果您从磁盘读取模板文件并且没有指定编码,则node.js将返回一个缓冲区。该错误基本上是相同的,因为Underscore期望一个字符串。确保您指定了编码,以便向Underscore传递一个字符串。
这将产生错误。
var template = _.template(fs.readFileSync('mytemplate.tpl'));

而且这很好。

var template = _.template(fs.readFileSync('mytemplate.tpl', { 'encoding':'utf8'}));

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接