Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Backbone Boilerplate Template

I'm very new to backbone but I manage to get it working from tutorial. But when I want to port those application to the backbone boilerplate I find myself stuck at the template. How do I access my model from my template? or even from the js file itself? I find myself stuck here for awhile now.

Backbone Boilerplate refers to https://github.com/tbranyen/backbone-boilerplate

like image 863
Athiwat Chunlakhan Avatar asked Oct 08 '22 08:10

Athiwat Chunlakhan


1 Answers

For most javascript templating libraries, templating occurs in two phases.

  1. 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.
  2. 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") %>.

like image 169
Peter Lyons Avatar answered Oct 12 '22 10:10

Peter Lyons