CanJS - Embeddedjs

canjs

What is can.EJS?

CanJS comes with the EmbeddedJS ( templating engine that looks like ERB) built in, but you can use any engine you prefer. can.EJS use EmbeddedJS.

// in devs.ejs
<% if( devs ) { %>
  <% for( var i = 0; i < devs.length; i++ ) { %>
    <li><%= arr[i] %></li>
  <% } %>
<% } else { %>
  <li>No Developers</li>
<% } %>

// render the template
can.view('devs.ejs',{devs: ['Andy','Fred']}) //-> fragment <li>Andy</li><li>Fred</li>

can.EJS provides automatic live binding when used with can.Observes, like in the following example:

// devs.ejs
<% if( devs.attr('length') ) { %>
  <% list(devs, function(dev){ %>
    <li><%= dev.attr(‘name’) %></li>
  <% }) %>
<% } else { %>
  <li>No Developers</li>
<% } %>

// create an observable list and render the template
var devs = new can.Observe.List([
  {name : 'Andy'}, {name : 'Fred'}
])

can.view('devs.ejs',{devs : devs}) //-> fragment <li>Andy</li><li>Fred</li>

EJS intelligently checks for use of the attr method. It binds to changes on the attributes it finds used in any template. When that attribute is changed, it updates the relevant part of the template. For example:

// change the observable data
devs.push({name: ‘Brian’});

When the length property changes the template’s event handler fires and adds an LI to the list.

What are the 3 types of magic tag supported by EJS within CanJS?

  1. <% CODE %> runs JavaScript code. This tag doesn't modify or populate the template, but allows you to use for loops, if/else statements, switch statements, and variable declarations inside the EJS template. Because almost any JavaScript code is valid in <% %>, EJS is incredibly powerful. Due to constraints necessary for live binding to function, it is heavily encouraged to only have one line of JS code per pair of EJS tags in order to ensure that the correct scope is maintained.
  2. <%= CODE %> runs a JavaScript statement, and writes the escaped result into the resulting HTML,
  3. <%== CODE %> runs a JavaScript statement and writes the unescaped result into the resulting HTML (used for sub-templates). The most common use of <%== %> is to include templates in other templates
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License