dbkaplun
dbkaplun

Reputation: 3637

How does one use a literal {{ in a Mustache template?

How does one use a literal "{{" in a Mustache template?

On a side note, if I'm using custom tags, like <% and %>, is there a way to write "<%"?

Theoretically, I could use different tags, but I have too much code written using {{ and }} to change it all.

Upvotes: 23

Views: 17159

Answers (5)

Jeff Camera
Jeff Camera

Reputation: 5544

You can also use a section lambda.

In mustache.js:

import Mustache from 'mustache';

const template = '{{ # literal }}{{Look at the curlies!}}{{ / literal }}';

const view = {
    literal: () => text => text
};

const output = Mustache.render(template, view);

console.log(output); // {{Look at the curlies!}}

Doing this of course means that nothing inside the literal section can be rendered which may or may not be desirable for your use case.

Upvotes: 0

Macondo
Macondo

Reputation: 166

You can achieve the result with just add a couple of curly braces in the template,
as example: data: const data = {"charsToBeEscaped": "<%"} template: a special char like that is perfectly rendered! {{{charsToBeEscaped}}}, it generates: is perfectly rendered! <%

Upvotes: 0

theK42
theK42

Reputation: 731

Just change the delimiters temporarily:

{{=<% %>=}}
{{Look at the curlies!}}
<%={{ }}=%>

Upvotes: 54

maxbeatty
maxbeatty

Reputation: 9325

You can use {{ by itself quite easily. If you are trying to document something like {{example}} you could always pass in the first two cur lies with your data.

orphaned curlies are easy {{ <br>
{{curly}}example}} curlies are harder

Some simple rendering:

var data = { 'curly' : '{{'},
    tpl = $('#curly').html(),
    html = Mustache.to_html(tpl, data);

document.write(html);​

Results in:

orphaned curlies are easy {{ 
{{example}} curlies are harder

Here's the full working jsFiddle

Upvotes: 3

Paul
Paul

Reputation: 141839

Assuming you are outputting HTML you could use an HTML entity to avoid it (mustache doesn't have any way to escape the opening tag built in).

So to output {{ you would write &#123;{.
To output <% you would write &lt;%.

Upvotes: 3

Related Questions