Search code examples
javascriptextjsextjs3

how to repeat tpl blocks inside tpl


I have a boxcomponent that I'm creating with a tpl. So in initTemplate I set the template I want by doing

this.tpl = new Ext.Xtemplate( my_template ).

So in my_template, which is a bit long actually, I have a block which I wish to repeat more than once inside my_template. What's the best way to achieve that? I wish I didn't have to copy the block over and over, specially if that block is long.

for example, let's say that 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>'

my data looks like:

data = {
 value1: {
   a: 'blah',
   b: 'bleh'
 }
 value2: {
   a: 'bloh',
   b: 'bluh'
 }
}

So, in my example, I'd like to know if there's a way to sort of call a function that will repeat

'<div class="c1">{a}</div>',
'<div class="c2">{b}</div>', 

So I'd have

'<tpl for="value1">',
    myFunction();
'</tpl>'

'<tpl for="value2">',
    myFunction();
'</tpl>'

Solution

  • Now it is entirely different question, after you have edited it. Nevermind, the answer is yes, you can use member functions to generate the content. This is example from XTemplate docs. As you can see, anything returned from isBaby and isGirl methods below is rendered in the resulting html. You only need to set myFunction and then call it within the template: 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);
    

    And 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 }
        ]
    };