在 mustachejs 中以未转义 html 呈现变量

render a variable in unescaped html in mustachejs

我知道使用 3 个括号会取消转义 html 但是如果这个 html 有一个我想渲染的变量怎么办,例如

{
 body: "<p> this is a {{message}} </p>",
 message: "Hello World"
}
{{{ body }}}

渲染

this is a

我希望它是

this is a Hello World

如果你想获取对象本身的值你需要使它return你想要在可以引用的函数调用中构建的字符串this

下面显示的 wat 是普通的 javascript。

<p id="test"></p>

<script>
    var item = {
     message: "Hello World",
     get body() { 
        return "<p> this is a " + this.message + "</p>" 
      }
    };

    document.getElementById("test").innerHTML = item.body;
</script>

参考link:https://clubmate.fi/self-referencing-object-literal-in-javascript/

根据文档,这是不可能的:

Lambdas

When the value is a callable object, such as a function or lambda, the object will be invoked and passed the block of text. The text passed is the literal block, unrendered. {{tags}} will not have been expanded - the lambda should do that on its own. In this way you can implement filters or caching.

但是,由于您可以使用函数进行渲染,因此很容易将消息包含在渲染函数中:

let view = {
  message: "message in a bottle ",
  body() {
    return `<p> this is a ${this.message}. </p>`
  }
}

let output = Mustache.render("{{{ body }}}", view)
console.log(output)
<script src="https://cdn.jsdelivr.net/gh/janl/mustache.js@v3.1.0/mustache.min.js"></script>

如果您的目标只是将 body 包裹在 <p> 中,最优雅(并且适合 doc)的解决方案是:

let view = {
  message: "message in a bottle ",
  body() {
    return (text, render) => `<p>${render(text)}</p>`
  }
}

let output = Mustache.render(`
{{#body}}
  This is a {{message}}.
{{/body}}
`, view)
console.log(output)
<script src="https://cdn.jsdelivr.net/gh/janl/mustache.js@v3.1.0/mustache.min.js"></script>