Search code examples
javascriptunderscore.jsunderscore.js-templating

UnderscoreJS template escapes JS operators


I'm having an issue where JavaScript operators in my UnderscoreJS Template are escaped and therefore unusable.

Escaped characters that I found are &&, >, <.

I've looked for another similar issue but couldn't find any.

Where is the problem?

My template is:

<div class="list-feedbacks-container" style="display: block;">
    {{ _.each(collection, function(model) {

        if (model.id > 0)
        {
            // This can't be execute, the line above raised an error
        }
    }}
</div>

The error raised in Firebug is:

SyntaxError: missing ) after condition
    if (model.id &gt; 0)                        {                            //

Firebug error

Here's my view:

Backbone.View.extend({
    el: '.list-container',

    events: {
        ...
    },

    /**
     *  Initiliaze the view variables and listeners of the view
     */
    initialize: function(){

        // Change delimiter from <% %> to {{ }}
            _.templateSettings = {
            interpolate: /\{\{\=(.+?)\}\}/g,
            evaluate: /\{\{(.+?)\}\}/g
        };

        this.collection = new myCollection();

        this.render();
    }
});

Thanks


Solution

  • Don't store your templates inside <div>s or anything else that is HTML. Anything that is considered to be HTML by the browser will be corrected to be valid HTML and templates are rarely going to be valid HTML. The result is a confusing mess.

    Instead, store your templates inside a container whose contents will be left alone. Usually you use a <script> with an appropriate content type:

    <script id="whatever" type="text/x-underscore-template">
        <div class="list-feedbacks-container" style="display: block;">
            {{ _.each(collection, function(model) {
                ...
            }}
        </div>
    </script>
    

    Then you can

    var t = _.template($('#whatever').html());
    

    to get your template functions without interference.