Template
Create an instance of template. Extend this.data
with data
, and assign template
to this.template
;
This is basically a view-model: you can set view-centric properties/methods to it and access them from the template itself using the tpl
model:
<div data-template="my_tpl">
<span data-text="tpl.name"></span>
</div>
<script>
var tpl = new witch.Template({}, 'my_tpl');
tpl.name = 'The Witch From The West';
tpl.render();
</script>
Returns this
(the Template instance).
Get the template using config.template()
, assign the returned element to this.el
, and bind this.data
to it. Then call fn
, if present, or this.ready
if fn
is not false.
var tpl = new witch.Template({}, 'my_tpl');
tpl.render(function() {
console.log('template is ready!');
});
Is called when this.render
finishes, unless the last was called with an argument.
Does nothing. Overwrite it with what you want to do with this.el
, for example:
var Tpl = witch.inherit(witch.Template, {
ready: function() {
this.el.appendTo('body');
}
});
var tpl = new Tpl;
tpl.render(); // ready() was called.
tpl.render(false); // ready() was not called.
callback
is called with err
and el
(a jQuery element)
Find a template by the name of tpl
, return by callback the a jQuery element generated from it. By default, witch comes with a simple implementation that searches for [data-template="tpl"]
, but it can be easily overriden to play with your choice of templating engine:
// vanilla js
var templates = { 'person': '<div />', ... };
witch.config.template = function(tpl, data, cb) {
var html = templates[tpl];
cb(!html, $(html));
}
// dust.js (precompiled)
witch.config.template = function(tpl, data, cb) {
dust.render(tpl, data, function(err, out) {
cb(err, $(out));
});
};
// handlebars (compile from element)
witch.config.template = function(tpl, data, cb) {
var template = Handlebars.compile($('#' + tpl).html()),
html = template(data);
cb(!html, $(html));
};
// handlebars (precompiled)
witch.config.template = function(tpl, data, cb) {
var html = Handlebars.templates[tpl](data);
cb(!html, $(html));
};
Please remember: Rivets.js, over which witch is build, is itself a templating solution, and a damn good one, as it allows the data to change with no need to rerender the template. Using another templating alongside it is usually not the best idea.