NSFW DISCLAIMER: You recognize that any simalarity to ES3 is purely coincidental and that all psuedo-code is just that and you hereby swear that you would never enter something as idiotic as document.write or escape into an actual JavaScript interpreter. Copying any of these snippets could and should get you fired and blacklisted. (in fact, I'm not sure that I shouldn't be fired for writing said psuedo-code)


Mustache is hard to explain only because it's so simple. You expect there to be more, but then... there isn't.

Check it out: http://mustache.github.io/mustache.5.html


{ user: 
  { name: "joe"
  , fb_url: "http://fb.com/joe"
  , bio: "I'm the flippin' <script>alert('bobby \'; drop tables;');</script>"

(consider the data above and some template like these)


{{# user }}
  Hello, {{ name }}!
{{/ user }}
if (user) { with (user) { document.write(escape("Hello", + name)); } }

if not

{{^ user }}
  Welcome Guest
{{/ user }}
if (!user) { document.write(escape("Welcome Guest")); }


{{ user.bio }}


{{{ user.facebook_url }}}


This would be the partial, as an object that is passed in at runtime:

{ friend_list: "{{ age }}, {{ sex }}, {{ location }}"
{{# friends }}
  {{> friend_list }}
{{/ friends }}
for (x in friends) {
  + ", "
  + escape(friends[x].sex)
  + ", "
  + escape(friends[x].location))

What about loops?

lists are handled automatically (as they should be!), like this:

{{# books }}
  {{ title }} by {{ author }}
{{/ books }}

But I usually see partials where lists would be.


Sometimes you want to use {{ just to mean {{.

For example, this blog post was rendered by Desi, which uses Mustache at every stage of the templating process.

If I hadn't have begun this post with {{=[% %]=}} to arbitrarily change the mustache syntax to use [% instead of {{, then I would have a mostly empty post (can't use <, because it gets escaped by markdown unless it's part of a valid html tag).

Just to test that theory: now you see me and ! (if you didn't see "and now you don't", then my little trick worked)

Likewise, if I update to some mustache implementation that doesn't support that... well, this post gets a lot shorter.


(the end)

It's okay to want there to be more. But there just isn't.

By AJ ONeal

If you loved this and want more like it, sign up!

Did I make your day?
Buy me a coffeeBuy me a coffee  

(you can learn about the bigger picture I'm working towards on my patreon page )