GitXplorerGitXplorer
f

context-template

public
0 stars
0 forks
0 issues

Commits

List of commits on branch master.
Unverified
484549d3801b5f6d4718631a79a2f5cb8abf6e8d

Indents & amd for 3 y.o. code

ffantactuka committed 11 years ago
Unverified
dae3623d79d93676b53212614376b6950b3f7943

Adding hashCode helper to use hash as cache key. Hello 3 y.o. code

ffantactuka committed 11 years ago
Unverified
050e64bf62a87ad78414bb11e5e1d4039e1b50a7

Edited README.md via GitHub

ffantactuka committed 13 years ago
Unverified
0c2865256583c2e835fa3d98b38f0b1809128f90

Readme again

ffantactuka committed 13 years ago
Unverified
61bee7a5d40727cde6b0bf7710d8c19a5b4bfb6b

Readme

ffantactuka committed 13 years ago
Unverified
50441410aaf2eeefc19ff635e8c17df95d04dcca

Readme changes, added spec for missed vars

ffantactuka committed 13 years ago

README

The README file for this repository.

Context Template

Context based version of Underscore.js (https://github.com/documentcloud/underscore) micro-templating. General difference is to use object context, instead of with(object) { } statement. It solves problems with undefined variable issues and makes easier to handle it:

Underscore

var html = "<div><%= surname %></div>";
_.template(html, { }); // Will throw "ReferenceError: surname is not defined"

so need to handle that like:

var html = "<div><% if(typeof surname != 'undefined') { %><%= surname %><% } %></div>";
_.template(html, { }); // <div></div>

ContextTemplate

var html = "<div><%= this.surname %></div>";
CT(html, { }); <div></div>

How to use

Assume that ContextTemplate function is assigned to CT global variable:

var html = "<div>Name: <%= this.name %> <% if(this.surname) { %><br/>Surname: <%= this.surname %><% } %></div>";
CT(html, { name: "Bob", surname: "Jones" }); // <div>Name: Bob<br/>Surname: Jones</div>

Also it's possible to use @ as a shorthand for this.:

var html = "<div>Name: <%= @name %> <% if(@surname) { %><br/>Surname: <%= @surname %><% } %></div>";
CT(html, { name: "Bob" }); // <div>Name: Bob<br/>Surname: Jones</div>

Caching

The other difference is lazy caching, instead of manual caching in _.template. Whenever template function is called for html string, "compiled" result will be saved in cache and next time same template called - cached version will be used:

Underscore

var html = "<div><%= name %></div>";
var compiledHTML = _.template(html); // Stores "compiled" template
compiledHTML({ name: "Bob" }); // Use cached template, just apply new variables
compiledHTML({ name: "Sam" }); // Use cached template, just apply new variables

ContextTemplate

var html = "<div><%= @name %></div>";
CT(html, { name: "Bob" });  // Stores "compiled" template
CT(html, { name: "Sam" });  // Use cached template, just apply new variables