开发者

How do I recursively nest smarty {foreach} loops while still being able to use {$smarty.foreach.<loopName>.first/last}?

开发者 https://www.devze.com 2022-12-16 17:29 出处:网络
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 recursivel

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?


Maybe try

{assign var="chSuffix" value="childrenLoop_$suffix"}
{foreach from=$children item="child" name="$chSuffix"}
    {$smarty.foreach.$chSuffix.total}
{/foreach}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号