[英]render a variable in unescaped html in mustachejs
I know that using 3 brackets will unescape html but what if this html has a variable that I want to render eg我知道使用 3 个括号会转义 html 但是如果这个 html 有一个我想要呈现的变量,例如
{
body: "<p> this is a {{message}} </p>",
message: "Hello World"
}
{{{ body }}}
renders渲染
this is a
I want it to be我希望它是
this is a Hello World
If you want to get the value of the object itself you need to make it return the string you want to build in a function call that can reference this
如果要获取对象本身的值,则需要使其返回要在可以引用
this
的函数调用中构建的字符串
The wat shown below is plain javascript.下面显示的 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>
reference link: https://clubmate.fi/self-referencing-object-literal-in-javascript/参考链接: https : //clubmate.fi/self-referencing-object-literal-in-javascript/
According to the doc, this is not possible:根据文档,这是不可能的:
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.
当值是一个可调用对象时,例如函数或 lambda,该对象将被调用并传递文本块。 The text passed is the literal block, unrendered.
传递的文本是未渲染的文字块。 {{tags}} will not have been expanded - the lambda should do that on its own.
{{tags}}不会被扩展 - lambda 应该自己做。 In this way you can implement filters or caching.
通过这种方式,您可以实现过滤器或缓存。
However, since you can use functions for rendering, it is easy to include the message in your rendered function:但是,由于您可以使用函数进行渲染,因此很容易在渲染的函数中包含消息:
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>
If your goal is only to wrap your body in a <p>
, the most elegant (and fitting to the doc ) solution would be:如果您的目标只是将您的身体包裹在
<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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.