Underscore.js template variable name is being escaped causing it to not get rendered

Viewed 25

I am playing around with rendering templates using with Underscore.js (Backbone.js app). I'm running into the following issue, where a part of the variable name in the template I am trying to render gets escaped when I try and obtain the template string (using .html(), .text()):

HTML file:

        <script type="text/template" id="tpl-note-item">
            <h1> 
                <%= noteTitle %>
            </h1>
        </script>

.js:

        var htmlString = $("#tpl-note-item").html();


        //   <h1> 
        //        &lt;%= noteTitle %>
        //    </h1>
        //
        console.log(htmlString); 

        var template = _.template(htmlString);

        html += template({ 
            noteTitle: note.get("title")
        });
        . . .

As a result of <%= noteTitle %> being escaped to &lt;%= noteTitle %>, the template gets rendered as:

<%= noteTitle %> instead of actually substituting in the variable value from the call to note.get("title").

This seems like a fairly basic use case of templates, so I am fairly sure I'm missing something. Any help would be much appreciated. Thanks!

1 Answers

Just minutes after posting this (and a day grappling with this), I found the issue: The HTML page in context is being rendered by my Golang app using:

template.Must(template.ParseFiles(<page.html>))

However, I was using the package html/template, which auto-escapes any html file being rendered. Switching to text/template did the trick. For reference, a related Golang post: Template unnecessarily escaping `<` to `&lt;` but not `>`

Related