Template
Template is a simple way for creating view of a component.
A template is a HTML text fragment containing template tags. There is two ways to use template :
- By expanding tags using values provides in an Object
- By generating a vs.ui.View with properties linked to tags
Before you begin
Some useful resources:Basic usage
Typical template description
var str = '<span style="color:${color}">name:${lastname},${firstname}</span>';
Expanding the template
var myTemplate = new Template (str);
var values = {
lastname : "Doe",
firstname : "John",
color : "blue"
};
console.log (myTemplate.apply (values));
// -> <span style="color:blue">name:Doe,John</span>
Generating a vs.ui.View from the template
var myTemplate = new Template (str);
var myView = myTemplate.compileView ();
myApp.add (myView);
// property changes, automatically update the DOM
myView.lastname = "Doe";
myView.firstname = "John";
myView.color = "blue";
The previous example creates a new component 'myView':
- with a view build from the template
- with 3 new properties "lastname", "firstname" and "color"
- the modification of one of these properties will change the node value.
Create multiple views from the same template
In many case, developer needs to reuse the same template in order to create multiple views. Instead of instantiate n templates for n views, that will take time and use lot of memory, it better to build the views from the same template instance.First solution: use compileView
var myTemplate = new Template (str);
var myView1 = myTemplate.compileView ();
myApp.add (myView1);
var myView2 = myTemplate.compileView ();
myApp.add (myView2);
Second solution: use clone
var myTemplate = new Template (str);
var myView1 = myTemplate.compileView ();
myApp.add (myView1);
var myView2 = myView1.clone ();
myApp.add (myView2);
Iterate on data
Iteration on array of objects
var str = '\
<div class="tels"> \
<div data-iterate="tels">${tel}</div> \
</div>';
var myTemplate = new Template (str);
var myView = myTemplate.compileView ();
myView.tels = [{tel: '080 6555 8899'}, {tel: '080 5785 55445'}]
Iteration on array of scalare
var str =
'<div class="tels"> \
<div data-iterate="tels">${@}</div> \
</div>';
var myTemplate = new Template (str);
var myView = myTemplate.compileView ();
myView.tels = ['080 6555 8899', '080 5785 55445']
© 2013 David Thevenin, ViniSketch, IGEL.