For most javascript templating libraries, templating occurs in two phases.
- Pass a string (usually containing HTML) to the template engine's "compilation" function. This returns you a "template function" you can execute. This only needs to happen once per template for the lifetime of your application.
- Render the template into output (usually HTML) by invoking the compiled template function and providing a "context" of data that will be available to the template. This can be done repeatedly with different context data to output different HTML.
.
//Compile your template string into a function
//Happens 1 time only then you can cache the function
var templateFunction = _.template("<p>Your <%- part %> is so <%- description %></p>");
//Generate your output HTML with varying sets of data.
var html1 = templateFunction({part: "nose", description: "big"});
//html1 has "<p>Your nose is so big</p>";
var html2 = templateFunction({part: "cat", description: "fat"});
//html2 has "<p>Your cat is so fat</p>";
This is the same basic idea for underscore templates, JST, jade, and most other templating engines. The "context data" is how your template gets access to your model. If you want, you can give it direct access to the underlying model by providing a context like: {model: myModel};
. Then in your template you could do something like <%= model.get("displayName") %>
.