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
Related Q & A:
- How To Create A Profile In Facebook?Best solution by Yahoo! Answers
- How To Create A Forum?Best solution by Super User
- How to create a custom email template?Best solution by Salesforce
- How to delete a line from a .txt file in node.js?Best solution by c-sharpcorner.com
- How to create a Database in FoxPro and how to retrieve and sort it out?Best solution by Yahoo! Answers
Just Added Q & A:
- How many active mobile subscribers are there in China?Best solution by Quora
- How to find the right vacation?Best solution by bookit.com
- How To Make Your Own Primer?Best solution by thekrazycouponlady.com
- How do you get the domain & range?Best solution by ChaCha
- How do you open pop up blockers?Best solution by Yahoo! Answers
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.