node.js 和 Handlebars : HTML compiled is escaped

标签 node.js handlebars.js template-engine html-escape-characters

我在 Node 应用程序中使用 Handlebars ,我遇到了麻烦。

这是模板 index.html

{{CONTENT}}

这是代码

var fs = require("fs");
var handlebars = require("handlebars");

var data = {
    CONTENT: "<b>Hello world!</b>"
};

var templateFile = fs.readFileSync('./index.html', 'utf8');
var template = handlebars.compile( templateFile );
var html = template(data);

问题在于标签 <B>转义到 &lt;B&gt;

我怎样才能避免这种情况?

最佳答案

来自 handlebarsjs.com :

Handlebars HTML-escapes values returned by a {{expression}}. If you don't want Handlebars to escape a value, use the "triple-stash".

<div class="entry">
  <h1>{{title}}</h1>
  <div class="body">
    {{{body}}}
  </div>
</div>

在这种情况下:

{
  title: "All about <p> Tags",
  body: "<p>This is a post about &lt;p&gt; tags</p>"
}

结果:

<div class="entry">
  <h1>All About &lt;p&gt; Tags</h1>
  <div class="body">
    <p>This is a post about &lt;p&gt; tags</p>
  </div>
</div>

但是从我的角度来看,它可能会破坏将模板分开而不是 js 文件的目的。

如果您使用 precompile然后使用 noEscape 选项:

handlebars.precompile(content, {noEscape: true})

关于node.js 和 Handlebars : HTML compiled is escaped,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15807799/

相关文章:

带数组的 JavaScript 字符串格式

javascript - 如果条件未在 ember 中传递正确的值

javascript - 具有压缩功能的 Node.JS http 服务器 - 发送变量作为响应

javascript - emit() 不工作 [Node.js]

javascript - Ember js 和 Handlebars - 每个都不起作用

ember.js - 为什么bindAttr 不能与disabled 一起使用?这是一个错误吗?

python - 什么时候在 Python 中使用模板引擎?

backbone.js - Handlebars 嵌套对象

html - go - 使用继承渲染 html/模板

json - 从 JSON 文件中删除 JSON 对象