Skip to content

Templates

Jason edited this page Jun 25, 2014 · 2 revisions

Lazo uses templates to render views. A template can be anything that meets the following criteria.

  • It is environment agnostic, i.e., there are no dependencies on the browser or Node
  • It returns a string
  • It is able adhere to the Lazo template engine interface
  • It can be loaded via RequireJS in both Node and the browser

By default Lazo uses Handlebars. Underscore's template engine is also available - "micro" is the name lookup.

Template Interface

A template engine needs to be registered with Lazo before it can be used in the Lazo rendering life cycle. This is done via LAZO.app.registerTemplateEngine.

define(['app/utils/nunjucks'], function (nunjucks) {

    'use strict';

    // 1. name of the template engine
    // 2. template file extension
    // 3. handler object with compile, precompile, & execute methods; reference to the engine
    // 4. path to template lib (optional if name is the module id)
    LAZO.app.registerTemplateEngine('nunjucks', 'njs', {
        compile: function(template) {
            return nunjucks.compile(template);
        },
        precompile: function (template) {
            return nunjucks.precompile(template);
        },
        execute: function(template, context) {
            return template(context);
        },
        engine: nunjucks
    }, 'app/utils/nunjucks');

});

Methods and Properties

In addition to registerTemplateEngine LAZO.app has many other template related methods.

getDefaultExt

Returns the default template file extension.

setTemplateExt

Sets a template engine file extension.

// engine name, extension
LAZO.app.setTemplateExt('handlebars', 'html');

getTemplateEngine

Gets a template engine handler/interface.

// engine name
LAZO.app.getTemplateEngine('handlebars');

getTemplateExt

Gets a template extension.

// engine name
LAZO.app.getTemplateExt('handlebars');

getTemplateEngineDef

Gets a template engine definition.

// engine name
LAZO.app.getTemplateEngineDef('handlebars');

getDefaultTemplateEngine

Gets the default template engine for an application.

getDefaultTemplateEngineName

Gets the default template engine name for an application.

setDefaultTemplateEngine

Sets the default template engine for an application.

// engine name
LAZO.app.setDefaultTemplateEngine('micro');

loadTemplateEngine

Loads a template engine.

var engineDef = LAZO.app.getTemplateEngineDef('nunjucks');

LAZO.app.loadTemplateEngine(engineDef, {
    success: function (templateEngine) {
        // do something with the engine
    },
    error: function (err) {
        throw err;
    }
});