Skip to content

Conversation

@balihoo-anewman
Copy link

In our application, we sometimes need to embed Javascript variables:

<p>Hello, {{name}}.</p>
<script>
  var x = {{{x}}};
</script>

However, in order to do this, we've had to call JSON.stringify from the calling code before rendering the template:

mustache.render('...', {
  name: 'thomas',
  x: JSON.stringify([1, 2, 'asdf']),
});

It's easy to forget which variables must be stringified, and which shouldn't be. This is because mustache is designed to emit HTML. However, JS is such an integral part of HTML, it deserves its own emitting mode.

Additionally, JSON.stringify actually can't even be relied upon to emit correct JS (http://timelessrepo.com/json-isnt-a-javascript-subset). The string JSON.stringify('\u2028'), for instance, is an invalid JS string, because it contains a line separator.

This commit implements a new filter which will emit JS. The above template would be written:

<p>Hello, {{name}}.</p>
<script>
  var x = {{js&x}};
</script>

The js& tag was chosen arbitrarily. Any other tag would work just as well.

@phillipj
Copy link
Collaborator

phillipj commented Jan 6, 2015

Seems like a great feature which shows the need for plugins / pragmas as mentioned in #406?

@brandonros
Copy link

What is the proper way to do this now?...

@Mygod
Copy link

Mygod commented Oct 2, 2020

An alternative way to do this: JSON.stringify(JSON.stringify([1, 2, 'asdf'])).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants