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.


{include file="menu-recursive.tpl" menu=$menu depth=1}


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

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')


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 …