tags:

views:

612

answers:

1

I have a Smarty template file in which I'm looping over hierarchical data represented by nested arrays. The child data is represented exactly the same way as the parent data, so I wanted to recursively {include} the Smarty template to render this:

Source of "my.tpl":

{foreach from=$children item="child" name="childrenLoop"}
    {* display stuff here *}
    {if $smarty.foreach.childrenLoop.last}
        {* do something special here when it is the last item *}
    {/if}

    {assign var="grandChildren" value=$child->getChildren()}
    {if $grandChildren|@count > 0}
        {include file="my.tpl" children=$grandChildren}
    {/if}
 {/foreach}

My problem is that when the {include} finishes executing, $smarty.foreach.childrenLoop.* tells me about the {include}'s loop, not the current loop. So if the inner loop had 10 items and the outer loop has 5, {$smarty.foreach.childrenLoop.total} will be 10 when I exit the inner loop, rather than 5. Needless to say, this is messing up my output.

I thought I could get around this problem by suffixing the loop with a value passed along by the include. I seem to be able to name the loop correctly:

{foreach from=$children item="child" name="childrenLoop_`$suffix`"}

... but I can't figure out how to access its properties, and the Smarty manual is not helpful:

{$smarty.foreach.childrenLoop_$suffix.total} {* NOPE! *}
{$smarty.foreach[childrenLoop_$suffix].total} {* NOPE! *}

What can I do here?

+1  A: 

Maybe try

{assign var="chSuffix" value="childrenLoop_$suffix"}
{foreach from=$children item="child" name="$chSuffix"}
    {$smarty.foreach.$chSuffix.total}
{/foreach}
hsz
Ah, I hadn't considered saving the entire naming convention into a variable.I had to make a small correction ( the correct syntax is {assign var="chSuffix" value="childrenLoop_$suffix"} ), but it worked! Thanks!!!Can you please edit your post with the correct syntax?
Mike