janl/mustache.js — pull request #358 by balihoo-anewman (2014-02-18 01:28:09+00:00)
Title: Add a filter for emitting JS data

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

Hello, {{name}}.

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:

Hello, {{name}}.

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