PDA

View Full Version : How to test if an element is the last in a XTemplate for loop?



Ozone
20 May 2010, 3:43 AM
Hi guys.

I have an XTemplate that loops through a serie of elements and writes them in some html format. After every element I print out a linebreak, but I don't want that extra linebreak to happen at the very last element.

Is there some clever way for the template to recognize that the element handled is the last one in the serie?

Here is some simplified example code:


var myData = [
{
msg: 'This is supposed to be bold',
adv: 'This is not'
},{
msg: 'This should be bold too and separated from the above by a breakline'
}
];

var myTemplate = new Ext.XTemplate(
'<tpl for=".">',
'<b>{values.msg}</b><br>',
'<tpl if="values.adv">',
'{values.adv}<br>',
'</tpl>',
'<br>',
'</tpl>'
);

myTemplate.applyTemplate(myData)
What I am looking for is something in the neighbourhood of this:



var myTemplate = new Ext.XTemplate(
'<tpl for=".">',
'<b>{values.msg}</b><br>',
'<tpl if="values.adv">',
'{values.adv}<br>',
'</tpl>',
'<tpl if="#!==values.parent.length">',
'<br>',
'</tpl>',
'</tpl>'
);
Except for "#!==values.parent.length" being something that evaluates true unless it is the very last element.

Any ideas?

evant
20 May 2010, 3:49 AM
Have you seen this sample?



var tpl = new Ext.XTemplate(
'<p>Name: {name}</p>',
'<p>Company: {[values.company.toUpperCase() + ", " + values.title]}</p>',
'<p>Kids: ',
'<tpl for="kids">',
'<div class="{[xindex % 2 === 0 ? "even" : "odd"]}">',
'{name}',
'</div>',
'</tpl></p>'
);
tpl.overwrite(panel.body, data);

steffenk
20 May 2010, 3:49 AM
it's in the docs:


Anything between {[ ... ]} is considered code to be executed in the scope of the template. There are some special variables available in that code:

* values: The values in the current scope. If you are using scope changing sub-templates, you can change what values is.
* parent: The scope (values) of the ancestor template.
* xindex: If you are in a looping template, the index of the loop you are in (1-based).
* xcount: If you are in a looping template, the total length of the array you are looping.
* fm: An alias for Ext.util.Format.

Animal
20 May 2010, 3:52 AM
Messing around on the Firebug command line always helps with XTemplates...



new Ext.XTemplate('<tpl for="."><tpl if="xindex==xcount">{.}</tpl></tpl>').apply(["foo", "bar", "bletch"])

Ozone
20 May 2010, 4:08 AM
Fantastic! :-)
Thanks a bunch everybody!