Displaying Recursive Data Structures with Smarty

For those of you who don’t know what smarty is, it is a PHP Templating-Engine whose main idea is to separate program logic from presentation.

A quite common task in web development is to display recursive data structures such as tree menus etc. However, this can be a bit tricky for someone new to smarty. There is currently no built in mechanism for doing so, but with the possibility to include sub files it can be done. Here is how it works.

menu.tpl

<h2>List</h2>
{include file="menu-recursive.tpl" menu=$menu depth=1}

menu-recursive.tpl

{foreach name=entry item=entry from=$menu.entries}
    {if $smarty.foreach.entry.first}
        <ul>
    {/if}         
    <li>
        {$entry}
        {if $menu.sub}
            {include file="menu-recursive.tpl" menu=$menu.sub depth=$depth+1}
        {/if}
    </li>
    {if $smarty.foreach.entry.last}
        </ul>
    {/if}
{foreachelse}
    <p>This category contains currently no entries.</p>
{/foreach}

PHP-file with the data structure.

$demo = array(
    'entries' => array('demo 1','demo 2'),
    'sub' => array(
        'entries' => array('demo 1.1','demo 2.1'),
        'sub' => array(
            'entries' => array('demo 1.1.1','demo 2.1.1')
        )
    )
);

$smarty->assign('menu',$demo);
$smarty->display('menu.tpl');

You should get a list looking similar to the one below.

  • demo 1
  • demo 2
    • demo 1.1
    • demo 2.1
      • demo 1.1.1
      • demo 2.1.1

However, whether a designer is able to understand this stuff is a completely different story …