Skip to content
robrobbins edited this page Aug 31, 2013 · 1 revision

sudo.template(source[, data][, name])

This implementaion piggybacks on J.Resig's initial micro templating post right along with all the others (Underscore, Dot etc...). Essentially, a string containing the delimiters described below can be:

  1. 'Compiled' into a reusable function by calling the sudo.template method and passing the string as the first argument. sudo.template(someString);. The function is returned in this case.
  2. 'Compiled' and 'expanded' with the desired values by passing the string as the first argument, and the (optional) object containing the data second. sudo.template(someString, someObject);

There is a third, also optional, argument that can be used to change the name of the 'promised' data object. More on that later.

###The Delimiters

  • Evaluate JavaScript: {{ var foo = 'bar'; }}
  • Output the value found in the passed in data object: {{= data.baz }}
  • Escapes and outputs the value found in the passed in data object: {{- data.qux }}

##Usage

An example reusable template:

<h1>{{= data.heading }}<h1>

<ul>
  {{ for (var i = 0; i < data.knights.length; i++) { }}
    {{ var knight = data.knights[i]; }}
    <li>
      <em>{{= knight.name }}</em>. favorite color: {{= knight.favoriteColor }}
    </li>
  {{ } }}
</ul>'

We will assume the above is a string saved in the variable tmpl. You could then 'compile' it to a function:

var compiled = sudo.template(tmpl);

###The data 'promise'

To avoid the use of a with statement, sudo templating demands that you append all of your data values to an imagined namespace, data by default. In the above example, data.heading is used to hydrate the value of the 'h1' tag. The data object you eventually pass to the compiled function then shold have a top level key, 'heading' - data, you see, is implicit. It is what the template calls the object you have sent it.

{
  heading: 'Knights and Their Favorite Color',
  knights: [{
    "name": "Lancelot",
    "favoriteColor": "blue"
  }, {
    "name": "Galahad",
    "favoriteColor": "unsure"
  }]
}

####Changing the Name of the Promise

If you want to use a different name (than the default 'data') for the implicit object, pass a string as the third argument to the template method. If tmpl was:

<h1>{{= foo.heading }}<h1>

<ul>
  {{ for (var i = 0; i < foo.knights.length; i++) { }}
    {{ var knight = foo.knights[i]; }}
    <li>
      <em>{{= knight.name }}</em>. favorite color: {{= knight.favoriteColor }}
    </li>
  {{ } }}
</ul>'

You would then:

sudo.template(tmpl, null, 'foo');

To return a function, or:

sudo.template(tmpl, someObject, 'foo');

To get the 'templated string'.

Clone this wiki locally