UnderscoreJS

From Organic Design wiki
Revision as of 16:19, 3 November 2015 by Nad (talk | contribs) ({{stub}})
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Cone.png This article or section is a stub. Stubs are articles that have not yet received substantial attention from the authors. They are short or insufficient pieces of information and require additions to further increase the article's usefulness. The project values stubs as useful first steps toward complete articles.


Templates

UnderscoreJS uses a very simple but efficient template system, the basic syntax is:

_.template( html, args );

Where the html source contains place-holders using <% and %> delimieters containing the names of properties to be filled from the args object. The property names are preceded by =, - or nothing depending on whether your property is a normal expression, needs escaping, or is raw JavaScript. See this good tutorial for more detail.

If the _.template function is called without the second parameter, then it will return a compiled version of the template in the form of a function that can be called with arguments when needed.

The following is a method I use for lazy-loading the templates, it's called with three parameters. The first is the name of the template which will be loaded from the templates directory and appended with ".html", the second is the arguments, and the third is a callback function which the final HTML populated with the arguments will be sent to. The first time a template is used it is loaded and compiled, and the callback is used to render an spinner icon while the template is first loading.

foo.template = function(template, args, fn) {

	// Create a list for the templates if not already existent
	if(!('templates' in this)) this.templates = [];

	// If the template is already loaded and compiled, process the final result immediately
	if(template in this.templates) fn(this.templates[template](args));

	// Otherwise load the template, and when it's loaded compile it and return the result
	else {
		fn('<div class="loading"></div>');
		$.ajax({
			type: 'GET',
			url: '/templates/' + template + '.html',
			context: this,
			dataType: 'html',
			success: function(html) {

				// Compile the template
				this.templates[template] = _.template(html);

				// Process the template with our args and send through the callback
				fn(this.templates[template](args));
			}
		});
	}
};

See also