Johann
Johann

Reputation: 4373

Mustache.js: How to avoid duplicating inner content when only opening tag differs?

I am sending my Mustache template in the page html (not as a separate request). Is there a way in mustache.js to avoid duplicating the inner content of an element when only the opening tag is different?

For example, in a browser-less environment I can use this contrived template:

{{#Person}}
<div class="hasperson">
{{/Person}}
{{^Person}}
<div class="noperson">
{{/Person}}
    <p>This line is the same regardless</p>
</div>

But in the browser, using mustache.js, I find I have to do the following so that the browser doesn't decimate the template html before Mustache has a chance to render it:

{{#Person}}
<div class="hasperson">
    <p>This line is the same regardless</p>
</div>
{{/Person}}
{{^Person}}
<div class="noperson">
    <p>This line is the same regardless</p>
</div>
{{/Person}}

I've considered using a partial, which would still require the closing tag of the div to be duplicated (not a bit deal), but I'd like to avoid this.

Upvotes: 0

Views: 1189

Answers (1)

kylealanhale
kylealanhale

Reputation: 1541

In order to prevent HTML-parser mangling like you're describing, I usually transmit my client-side templates as plain text, and then render them with the template engine and inject them into the DOM. If you want them in the same doc without making a separate request to fetch them, you can wrap them in script tags with a text/plain (or other non-executable) type attribute, and then you can get the template via the script's innerText.

    <!-- ... -->
    <script id="person-template" type="text/plain">
        {{#Person}}
        <div class="hasperson">
        {{/Person}}
        {{^Person}}
        <div class="noperson">
        {{/Person}}
            <p>This line is the same regardless</p>
        </div>
    </script>
    <!-- ... -->

There's a similar example here, with more complete sample code: https://github.com/janl/mustache.js/#include-templates

Upvotes: 2

Related Questions