Search code examples
javascriptunderscore.jsunderscore.js-templating

Can anyone explain Underscore's precompilation in _.template?


I read Underscore's docs, find in _.template:

Precompiling your templates can be a big help when debugging errors you can't reproduce. This is because precompiled templates can provide line numbers and a stack trace, something that is not possible when compiling templates on the client. The source property is available on the compiled template function for easy precompilation

I wonder what it means and how it's used.

I write the code below:

<div>
  <ul class="list">
    <li>apple</li>
    <li>orange</li>
    <li class="last-item">peach</li>
  </ul>
</div>

<script src="underscore.js"></script>

<script type="text/template" id="tpl">
  <ul class="list">
    <%_.each(obj, function(e, i, a){%>
      <% if (i === a.length - 1) %>
        <li class="last-item"><%=e.name%></li>
      <% else %>
        <li><%=e.name%></li>
    <%})%>
  </ul>
</script>

<script>
var data = [{name: "apple"}, {name: "orange"}, {name: "peach"}];
var compiled = _.template(document.getElementById("tpl").innerHTML);
var str = compiled(data);
document.querySelector("div").innerHTML = str;
</script>

It works well, and in my opinion, when I miss an > in the template, by precompiling it will tell me which line I miss the >, is that right? And how to do a demo? The following code may not work if straightly put, so how to make it useful?

<script>
  JST.project = <%= _.template(jstText).source %>;
</script>

Solution

  • JST is a server-side thing, not client-side. This mean that you compile Unserscore template on server side by some server-side script and save the result in a file. Then use this file as compiled Unserscore template.