XTemplate能夠很方便的在頁面中編寫一段可以使用數據倉庫中數據的html代碼。
官網中給出的XTemplate類的一些除了編寫html代碼之外的方法:
A template class that supports advanced functionality like:
- Autofilling arrays using templates and sub-templates
- Conditional processing with basic comparison operators
- Basic math function support
- Execute arbitrary inline code with special built-in template variables
- Custom member functions
- Many special tags and built-in operators that aren't defined as part of the API, but are supported in the templates that can be created
var tpl = new Ext.XTemplate(
'<p>Name: {name}</p>',
'<p>Kids: ',
'<tpl for="kids">',//for循環
'<p>{name} is a ',
'<tpl if="age >= 13">',
'<p>teenager</p>',
'<tpl elseif="age >= 2">',
'<p>kid</p>',
'<tpl else>',
'<p>baby</p>',
'</tpl>',
'</tpl></p>'
);
var tpl = new Ext.XTemplate(
'<p>Name: {name}</p>',
'<p>Kids: ',
'<tpl for="kids">',
'<p>{name} is a ',
'<tpl switch="name">',//switch語句,發現確實很屌的東西
'<tpl case="Aubrey" case="Nikol">',
'<p>girl</p>',
'<tpl default">',
'<p>boy</p>',
'</tpl>',
'</tpl></p>'
);
2.此外還有很多內置的模版的變量,內置變量的在{[ ]}之間,會被像{ }之間一樣被輸出;而在{% %}之間的語句則只是用來運行並且作爲判斷條件。比較常用的有values表示模版正在訪問的數據,xindex表示在對數組進行遍歷時,顯示當前數據項在數組中的序號(第一項爲1);xcount當數組進行遍歷時,表示數組中數據的條數。
'<tpl for="kids">',
'{% if (xindex % 2 === 0) continue; %}',
'{name}',
'{% if (xindex > 100) break; %}',//可以用來break the loop
'</div>',
'</tpl></p>'
3.在模版中使用自定義的函數,自定義的函數在配置選項中被定義
var tpl = new Ext.XTemplate(
'<tpl for="kids">',
'<tpl if="this.isGirl(name)">',
'<p>Girl: {name} - {age}</p>',
'<tpl else>',
'<p>Boy: {name} - {age}</p>',
'</tpl>',
'</tpl>',
{
// XTemplate configuration:
disableFormats: true,
// member functions:
isGirl: function(name){
return name == 'Sara Grace';
}
}
);
tpl.overwrite(panel.body, data);