Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add a filter for emitting JS data #358

Open
wants to merge 6 commits into
base: master
Choose a base branch
from

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.

None yet

5 participants