Sunday, December 19, 2010

Please Tell Me I Got This JavaScript Wrong

I wanted to code a naive implementation of Mustache templates in JavaScript.

If I read the JavaScript regex docs right, this is what I have to do:

mustached = "{{foo}} bar";
object = {foo: "baz"}
function(string, parens) { return string.replace(/\{\{([^\}]+)\}\}/,
// to get the result "baz bar"

In Perl, it'd be:

mustached =~ s/\{\{([^\}]+)\}\}/$hash{$1}/;

In JavaScript, you can't access a variable $1, only a string argument "$1" to replace, or parens, a string argument to a callback function.

I'm enjoying JavaScript for the most part - it's a Lisp with a beautiful object model and horrific syntax - but this is just silly.

(If you don't get the regex, read the Friedl book; it's great.)

Update: I got it wrong! Thank the Flying Spaghetti Monster. Lucas Luitjes clued me in to the better way:

[lucas@nicotine:~]$ node
Type '.help' for options.
node> var mustached = "{{foo}} bar";
node> var object = {foo: "baz"};
node> mustached.replace(/\{\{([^\}]+)\}\}/, function(m,p1) { return object[p1] });
'baz bar'

Also, I turned this into a tiny templater:

And, Adam van de Hoven made with the tweakage.