Cover by Alex MacCaw

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

O'Reilly logo

Using Client-Side Templates in the View

JavaScriptMVC’s views are really just client-side templates, which take data and return a string. Typically, the strings are HTML intended to be inserted into the DOM.

$.View is a templating interface that uses templates to take care of complexities. It offers:

  • Convenient and uniform syntax

  • Template loading from HTML elements or external files

  • Synchronous or asynchronous template loading

  • Template preloading

  • Caching of processed templates

  • Bundling of processed templates in production builds

  • $.Deferred support

JavaScriptMVC comes prepackaged with four different template engines:

  • EJS

  • JAML

  • Micro

  • Tmpl

This tutorial uses EJS templates, but the following techniques will work with any template engine (with minor syntax differences).

Basic Use

When using views, you almost always want to insert the results of a rendered template into the page. jQuery.View overwrites the jQuery modifiers, so using a view is as easy as:

$("#foo").html('mytemplate.ejs',{message: 'hello world'})

This code:

  1. Loads the template in the file mytemplate.ejs. It might look like:

    <h2><%= message %></h2>
  2. Renders it with {message: ‘hello world'}, resulting in:

    <h2>hello world</h2>
  3. Inserts the result into the foo element, which might look like:

    <div id='foo'><h2>hello world</h2></div>

jQuery Modifiers

You can use a template with the following jQuery modifier methods:

$('#bar').after('temp.ejs',{}); $('#bar').append('temp.ejs',{}); $('#bar').before('temp.ejs',{}); $('#bar').html('temp.ejs',{}); $('#bar').prepend('temp.ejs',{}); ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required