Search code examples
javascriptbackbone.jsunderscore.jsbackbone-viewsunderscore.js-templating

Create Multiple _.templateSettings in underScore.js


Is it possible to create multiple _.templateSettings in underscore.js?

Because few of my project HTML files follows '<% %>,<%=%>'

but in JSP it throws a compilation error.

I changed ERB styles to '<@ @>,<@= @>', etc. but they asked me to follow separate style for HTML and JSP.

I'm Struggling to create separate _.templateSettings.Otherwise we should create a method that should accept both '<% %>,<%= %>,<@ @>,<@= @>'etc.

I'm using backbone along with spring MVC.


Solution

  • Trying to set up separate _.templateSettings for each template is going to be messy and error prone. The regexes in _.templateSettings can be pretty much anything (as long as they have an appropriate capture group) so you can use regexes that match both <%...%> and <@...@> delimiters. Something like this:

    _.templateSettings = {
        evaluate    : /<[%@]([\s\S]+?)[%@]>/g,
        interpolate : /<[%@]=([\s\S]+?)[%@]>/g,
        escape      : /<[%@]-([\s\S]+?)[%@]>/g
    };
    

    should do the trick. That will let <% ... @> through of course but you can add the appropriate back-references to the regexes if you care about things like that.

    Demo: http://jsfiddle.net/ambiguous/9Mqr4/