简体   繁体   中英

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

{
 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

The wat shown below is plain 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/

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. 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.

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:

 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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM