All notes
Js

Basics

JST: JS template. By underscore.

Good references

2ality.com.

Inserting data



<%=interpolate%>

<%-escape%>
// Insert the result of an expression, but escape the following characters via _.escape():
//     & < > "" '' /

<%evaluate%>
// Evaluate the given code. This allows you to do loops and conditions.

print()



// The two versions are same:
"<%if (i>0) {%>, <%}%>"
"<%if (i>0) { print(', ') }%>"

The object "obj"



// The following expressions are equivalent:
_.template("Hello <%=user%>!", { user: "<Jane>" })
_.template("Hello <%=obj.user%>!", { user: "<Jane>" })

// Using "obj" makes it easier to check whether a property exists.
<%if (typeof title !== 'undefined') {%>Title: <%=title%><%}%>
<%if (obj.title) {%>Title: <%=title%><%}%>

Changing the syntax



// For example, you can use Mustache-style curly braces instead of angle brackets:
_.templateSettings = {
    interpolate : /\{\{(.+?)\}\}/g
};
// Interaction:
_.template("Hello {{user}}!", { user: "<Jane>" })
// 'Hello <Jane>!'

Compilation



_.template("a <%-esc%> b <%=inter%> c <%eval%> d");
// Compiled into a function:
function (obj) {
  var __p = [];
  function print() {
    __p.push.apply(__p,arguments);
  }
  with (obj || {}) {
    __p.push('a ', _.escape(esc), ' b ', inter, ' c ');
    eval;
    __p.push(' d');
  }
  return __p.join('');
}

FAQ

How to debug

Insert this line:



<% debugger %>