When an old Mustache partial wants {{.}} give him {.:v}

Javascript is full of weird “special” features. I’m reusing my Mustache-templates using Hogan.js for Express on the server and on the client side. Lately I noticed  that the  client-side ICanHaz template loader uses Mustache 0.4.0, a version that’s highly outdated. Let me show you what I tried.

When traversing arrays the {{.}} template variable comes in handy: it’s replaced with the “current” value. If you want to render an array of strings you do this (Mustache 0.4.0):

$ npm install mustache@0.4.0
$ node

var Mu = require('mustache');
var opts = {attrs: ["weird", "crazy","awesome"]};
var tpl = 'Javascript is {{#attrs}} {{.}} {{/attrs}}';
Mu.to_html(tpl, opts); //Mu 0.4.0

> 'Javascript is  weird  crazy  awesome '

More advanced, lets use partials (preregistered sub templates):

var partials = {part: "<b> {{.}} </b>" };
var tpl = 'Javascript is {{#attrs}} {{>part}} {{/attrs}}';
Mu.to_html(tpl, opts, partials);

> 'Javascript is  <b> weird </b>  <b> crazy </b>  <b> awesome </b> '

What if you would like to render the part-partial on its own for only one string, say “queer” ?:

var qu = "queer";
Mu.to_html(partials.part, qu)

> ‘<b>  </b>’


var qu = { ".":"queer" };
Mu.to_html(partials.part, qu);

> ‘<b> queer </b>’

First, I thought this is a major “flaw” in Mustache but on the server side I’m using the latest version (0.7.0) so I never noticed this behaviour before. Good thing: you can bring your own Mustache for ICanHaz if you don’t want to go the “.” way 🙂 Going to do that now.

In 0.7.0 you simply do:

var Mu = require('Mustache');
var partials = {part: "<b> {{.}} </b>" };
var qu = "queer";
Mu.render(partials.part, qu);

> ‘<b> queer </b>’

Lessons learned: object property names can be “.”. Another funny side-notice: you can also use keywords as property names, e.g. I recently have seen someone returning {“return”:”true”} in his AJAX calls. I doubt that this is good practice…


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s