Search code examples
javascripttemplatesunderscore.jsunderscore.js-templating

Can't get underscore.js to use curly braces without syntax error


Anyone know why this doesn't work? I'm trying to get _.template to use braces.

    _.templateSettings = { //change delimiter to <$ $>
          interpolate : /\<\$(.+?)\$\>/g
        };      
    var list = "<$ _.each(people, function(name) { $> <li><$ name $> </li> <$ }); $>";
    var html=_.template(list);
    console.log(html({people : ['moe', 'curly', 'larry']}));

It produces the following syntax error error at )):

((__t=( .each(people, function(name) { ))==null?'':_t)+

Here's what the Underscore documentation says:

If ERB-style delimiters aren't your cup of tea, you can change Underscore's template settings to use different symbols to set off interpolated code. Define an interpolate regex to match expressions that should be interpolated verbatim, an escape regex to match expressions that should be inserted after being HTML escaped, and an evaluate regex to match expressions that should be evaluated without insertion into the resulting string. You may define or omit any combination of the three. For example, to perform Mustache.js style templating:

_.templateSettings = { interpolate : /{{(.+?)}}/g };

var template = _.template("Hello {{ name }}!"); template({name : "Mustache"}); => "Hello Mustache!"


Solution

  • Your problem is that something interpolated should produce a stand-alone JavaScript expression and this:

    _.each(people, function(name) {
    

    is not a valid expression. You need to define separate evaluate and interpolate regexes and then use the evaluate one for the _.each; something like this:

    _.templateSettings = {
        interpolate: /\{\{=(.+?)\}\}/g,
        evaluate: /\{\{(.+?)\}\}/g,
    };
    var list = "{{_.each(people, function(name) {}} <li>{{=name}}</li> {{ }); }}";
    

    Note that interpolation now uses {{= ... }} and {{ ... }} is just for evaluating (or embedding) little JavaScript snippets.

    Demo: http://jsfiddle.net/ambiguous/SDmLz/