Search code examples
javascripttemplatesunderscore.jsunderscore.js-templating

How to partially substitute an Underscore.js template, or how to create a template from a template


I would create a master template for generating other templates. The only method I found is this one:

var test_tpl_master = _.template(
    "StackOverflow <%= type %> question number <%= num %>"
);

var test_tpl_1 = _.template(test_tpl_master({
    "type": "good", 
    "num": "<%= num %>"
}));

var test_tpl_2 = _.template(test_tpl_master({
    "type": "stupid", 
    "num": "<%= num %>"
}));

Is there not a more simple and elegant way?


Solution

  • You can create a function that will act as a proxy to your master and will fill the the variables you want.

    For example, let's say you have

    var prefill_template = function(tpl, defs) {
        return function(data) {
            return tpl(_.extend({}, data, defs));
        }
    }
    

    You can then create your subtemplates functions by

    var test_tpl_1 = prefill_template(test_tpl_master, {
        "type": "good"
    });
    
    var test_tpl_2 =  prefill_template(test_tpl_master, {
        "type": "stupid"
    });
    

    and use them as any other template :

    console.log(test_tpl_1({
        num: 1
    }));
    console.log(test_tpl_2({
        num: 1
    }));
    

    And a demo http://jsfiddle.net/nikoshr/qshb1zrx/