How to create a underscore template dynamically?

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?

  • Answer:

    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/

Marco Sulla at Stack Overflow Visit the source

Was this solution helpful to you?

Related Q & A:

Just Added Q & A:

Find solution

For every problem there is a solution! Proved by Solucija.

  • Got an issue and looking for advice?

  • Ask Solucija to search every corner of the Web for help.

  • Get workable solutions and helpful tips in a moment.

Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.