PDA

View Full Version : XTemplate "for" with conditional



timbellomo
11 Jan 2012, 2:12 PM
I'm looking for a way to get an accurate count out of the "for" loop in my XTemplate. I'm filtering out certain items in the loop. Because of this filtering, I can't use the "xcount" since it reflects the total including the items that are later filtered out.


...
'<tpl for="assignments">',
'<tpl if="cleared_at==null">',
'<li class="status status-{status_id}">{unit_name}</li>',
'</tpl>',
'</tpl>',
...


I need to get the count of displayed items, that is, items where "cleared_at==null." I did some experimenting with adding a conditional to the "for" like so:


...
'<tpl for="assignments" if="cleared_at==null">',
'<li class="status status-{status_id}">{unit_name}</li>',
'</tpl>',
...

...which doesn't work. Interesting, though, that a conditional like:


...
'<tpl for="assignments" if="1==1">',
'<li class="status status-{status_id}">{unit_name}</li>',
'</tpl>',
...
(which gives all records)
OR


...
'<tpl for="assignments" if="1==2">',
'<li class="status status-{status_id}">{unit_name}</li>',
'</tpl>',
...
(which gives no records)
...evaluates as you would expect, respecting the "if" statement. I just can't figure out how to test the items in the array. Is there a better way to accomplish this? I need to display the items and display a count of only the displayed items.

Thanks,
Tim

mitchellsimoens
12 Jan 2012, 7:26 AM
For this line: <tpl for="assignments" if="cleared_at==null">, I'm assuming cleared_at is a key of an object in the assignments array. The reason why it doesn't work is in that <tpl> the cleared_at being looked at at the parent object, not in the assignments array. You will need two <tpl> to accomplish this like the first code snippet. If you need the count, you can keep a variable and add to it.

timbellomo
12 Jan 2012, 8:58 AM
Your assumption is correct. Thanks for helping me understand the problem; I was hoping that there was some kind of built-in "where" as part of the "for" loop.

I had thought about declaring and incrementing a variable of my own in the loop, but couldn't figure out a way to do so. Is there some "<tpl var='foo'>" declaration syntax, as there is in xslt (xsl:variable)?