Ext Templates
by Ryan Morris
HTML
<div id="container">
<p>I am a container</p>
</div>
CSS
body {
background-color:#aeaeae;
}
#container {
background-color:#ccc;
}
JavaScript
/**
* Ext.Template
*/
// basic
// simple template with numbered "slots" for variable replacement
var myTpl = new Ext.Template("<div>Hello {0}.</div>");
myTpl.append(document.body, ['Ryan']);
myTpl.append(document.body, ['Sharon']);
myTpl.append(document.body, ['Tim']);
/*
var container = Ext.get('container');
myTpl.append(container, ['Ryan']);
myTpl.append(container, ['Sharon']);
myTpl.append(container, ['Tim']);
*/
// can take named args
// can accept any number of args as the template strings.. for formatting
var myTpl = new Ext.Template(
"<div>",
"Hello {name}, how is your {day} going.",
"</div>");
// for performance boost during render
myTpl.compile();
myTpl.append(container, {
name: "Ryan",
day: "Monday"
});
// Use XTemplate for more advanced logic in templates
// like conditionals and iteration and custom methods
var tplData = [{
name: "Ryan",
featured: true,
books: ['Cosmos', 'The Killer Angels', 'Omega']
}, {
name: "Tim",
featured: false,
books: ['Siddhartha', 'Thud!']
}];
var myTpl = new Ext.XTemplate(
'<tpl for=".">', // iterate
'<div ',
'<tpl if="this.isFeatured(values)">', // render if condition met
'class="featured"',
'</tpl>',
'>',
'<b>Name :</b> {name}<br />',
'<tpl for="books">', // iterate through books values
'{.}', // current value
// JavaScript can be wrapped by {[ ]}
// xindex is special value, current index
// xcount is special value, current number of items in array
'{[ (xindex < xcount) ? ", " : "" ]}',
'</tpl>',
'</div>',
'</tpl>',
// custom methods defined as last argument
{
isFeatured: function(values) {
//console.log(value);
return values.featured;
}
}
);
myTpl.compile();
myTpl.append(container, tplData);