Javascript Underscore.js 模板渲染

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8196091/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 05:03:40  来源:igfitidea点击:

Underscore.js template rendering

javascriptbackbone.jsunderscore.jsunderscore.js-templating

提问by fadzril

I have this sample code to render simple unescapedHTML using underscore templating.

我有这个示例代码来使用下划线模板呈现简单的非转义 HTML。

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

But when it try to render it, it caused an error:

但是当它尝试渲染它时,它导致了一个错误:

Uncaught TypeError: Object [object Object] has no method 'replace'

未捕获的类型错误:对象 [object Object] 没有方法“替换”

Can anyone please enlighten me what's the cause and how to solve it? Since in underscore documentation:

任何人都可以请教我是什么原因以及如何解决它?由于在下划线文档中:

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

Thanks in advance.

提前致谢。

回答by mu is too short

From the fine manual:

来自精美手册

template_.template(templateString, [context])

Compiles JavaScript templates into functions that can be evaluated for rendering.

模板_.template(templateString, [context])

将 JavaScript 模板编译为可用于渲染的函数。

The first argument for _.templateis supposed to be a string, not a jQuery object. Part of the internal processing for _.templatecalls the String#replacefunction and that's where your error comes from. You might want to use this instead:

for 的第一个参数_.template应该是一个字符串,而不是一个 jQuery 对象。_.template调用String#replace函数的内部处理的一部分,这就是错误的来源。您可能想改用它:

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

Demo: http://jsfiddle.net/ambiguous/wPu6G/

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

The example you give works just fine:

你给出的例子工作得很好:

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

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

So I don't know where the 'value' is not definederror you mention in your comment could be coming from.

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

回答by Michael Connor

I just hit the same error while running node on the server. If you read the template file from disk and you don't specify the encoding then node.js will return a buffer. The error is basically the same because Underscore expects a string. Make sure that you specify an encoding so that you are passing a string to Underscore.

我只是在服务器上运行节点时遇到了同样的错误。如果您从磁盘读取模板文件并且没有指定编码,那么 node.js 将返回一个缓冲区。错误基本相同,因为 Underscore 需要一个字符串。确保指定了编码,以便将字符串传递给 Underscore。

this will produce the error.

这将产生错误。

var template = _.template(fs.readFileSync('mytemplate.tpl'));

and this is good.

这很好。

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