开发者

Smarty nested foreach with associative keys

PHP:

<?php
$menu = array(
            array('label' => 'myLabel', 'submenu' =>
                array('label' => 'test label',
                    'label' => 'test label',
                    'label' => 'test label'
            )),
            array(...)
        );
 $smarty->assign(array('menu' => $menu));

TPL:

<ul>        
    {foreach from=$menu key=k item=elem}
    <li>
        <div>
            {$elem.label}
        </div>
        <ul>
            {foreach from=$elem.submenu item=subelem}
                <li>{$subelem.label}</li>
            {/foreach}
        </ul>

    </li>
    {/foreach}
</ul>

Note that arrays like $menu = array(array("A"), array("B"), array("C")); works fine.

Where am i wrong? Is it possible or smarty is unable to do that?


EDIT: Problem is: This outp开发者_如何学编程ut the first list, and the first letter of the first element of the child list in the proper html context.


What you did wrong

The inner foreach is where the problem is. Your item (subelem) in the inner foreach is not an array (as you thought), but it's a string.

Solution

This should work:

<ul>        
    {foreach from=$menu key=k item=elem}
    <li>
        <div>
            {$elem.label}
        </div>
        <ul>
            {foreach from=$elem.submenu key=label item=text_label}
                <li>{$text_label}</li>
            {/foreach}
        </ul>

    </li>
    {/foreach}
</ul>
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜