我有一个用tpl创建的boxcomponent。在initTemplate中,我通过
来设置我想要的模板this.tpl = new Ext.Xtemplate( my_template ).
在my_template中,实际上有点长,我有一个块,我希望在my_template中重复多次。实现这一目标的最佳方式是什么?我希望我不必一遍又一遍地复制这个块,特别是如果这个块很长的话。
例如,my_template ='<tpl for="value1">',
'<div class="c1">{a}</div>',
'<div class="c2">{b}</div>',
'</tpl>'
'<tpl for="value2">',
'<div class="c1">{a}</div>',
'<div class="c2">{b}</div>',
'</tpl>'
我的数据看起来像:
data = {
value1: {
a: 'blah',
b: 'bleh'
}
value2: {
a: 'bloh',
b: 'bluh'
}
}
那么,在我的例子中,我想知道是否有一种方法可以调用一个函数来重复
'<div class="c1">{a}</div>',
'<div class="c2">{b}</div>',
也就是
'<tpl for="value1">',
myFunction();
'</tpl>'
'<tpl for="value2">',
myFunction();
'</tpl>'
现在是完全不同的问题,在你编辑它之后。没关系,答案是肯定的,您可以使用成员函数来生成内容。这是来自XTemplate文档的例子。可以看到,下面isBaby
和isGirl
方法返回的任何内容都呈现在结果html中。您只需要设置myFunction
,然后在模板中调用它:this.myFunction()
var tpl = new Ext.XTemplate(
'<p>Name: {name}</p>',
'<p>Kids: ',
'<tpl for="kids">',
'<tpl if="this.isGirl(name)">',
'<p>Girl: {name} - {age}</p>',
'<tpl else>',
'<p>Boy: {name} - {age}</p>',
'</tpl>',
'<tpl if="this.isBaby(age)">',
'<p>{name} is a baby!</p>',
'</tpl>',
'</tpl></p>',
{
// XTemplate configuration:
disableFormats: true,
// member functions:
isGirl: function(name){
return name == 'Aubrey' || name == 'Nikol';
},
isBaby: function(age){
return age < 1;
}
}
);
tpl.overwrite(panel.body, data);
和数据:
var data = {
name: 'Don Griffin',
title: 'Senior Technomage',
company: 'Sencha Inc.',
drinks: ['Coffee', 'Water', 'More Coffee'],
kids: [
{ name: 'Aubrey', age: 17 },
{ name: 'Joshua', age: 13 },
{ name: 'Cale', age: 10 },
{ name: 'Nikol', age: 5 },
{ name: 'Solomon', age: 0 }
]
};
这取决于您提供给模板的数据是否也重复-如果它是一个数组。就像你有<tpl for=".">
一样,你也可以有<tpl for="innerArray">
,所以如果你的数据看起来像下面这样:
[
{item:'value', innerArray:[{
innerItem:'value1'
},{
innerItem:'value2'
}]}
]
new Ext.XTemplate([
'<tpl for=".">',
'<div>',
'<tpl for="list">',
'{[ this.getTemplateIfDataPresent(values, "key_a") ]}',
'{[ this.getTemplateIfDataPresent(values, "key_b") ]}',
'</tpl> ',
'</div>',
'</tpl>'
].join(""), {
compiled: true,
templateStr: '<p> {0}: <b>{1}</b> </p>',
getTemplate: function(values, key) {
if (!values || !values[key]) {
return '-';
}
var result = String.format(this.templateStr, key, values.list[key]);
return result;
}
});