Forum Moderators: coopster

Message Too Old, No Replies

Smarty and nested lists - arbitrary depth

can Smarty do it?

         

ergophobe

6:43 pm on Mar 4, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



I started a brand new site this morning, and thought maybe I would use it as the occasion to finally give one of the templating engines a try. Since Smarty is semi-official (it's at smarty.php.net after all), I settled on that one.

Now I'm about three lines into the new site and I'm stuck!

I have a function getCategoryTree which returns an array of categories that would look like this

$cats = array('cat1'=>array('catId', 'catName',
array('subcats'=>array('cata', 'catb').... you get the idea


cat1
cata
catb
cat2
cata
catb

The problem is, that I want to be able to set "max levels" in my settings file and have the presentation layer recurse until it reaches that point, just as it does when building the array. It would be easy with a php abstraction layer, but with Smarty I'm having trouble figuring out how to output an arbitrary-depth list. Is it possible with Smarty?

Truth be told, this all seems rather cumbersome compared to just using Plain Old PHP... not convinced of the benefits yet. For example, at just two levels deep, the Smarty code looks like:


<ul>
{section name=level1 loop=$nav_cats}
<li>{$nav_cats[level1].catId}: {$nav_cats[level1].catName}</li>
{section name=level2 loop=$nav_cats[level1].subcats}
{if $smarty.section.level2.first}
<ul>
{/if}
<li>{$nav_cats[level1].subcats[level2].catId} : {$nav_cats[level1].subcats[level2].catName}</li>
{if $smarty.section.level2.last}
</ul>
{/if}
{/section}
{/section}
</ul>

With a simple few lines of PHP and recursion I could go as deep as my computer had memory for without having to address variables in forms like

$nav_cats[level1].subcats[level2].catName

Since the current example is just for basic navigation, I can't imagine it would go beyond three levels, but in principle I don't like the idea that the depth is hard-coded. Still not seeing the benefits... but continuing to play!

Timotheos

7:01 pm on Mar 4, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



this all seems rather cumbersome compared to just using Plain Old PHP

Exactly, you're running into some of the reasons I dismissed Smarty. Why learn a new syntax when PHP can do it quite well? Did you consider phpSavant? It's a templating system that uses just plain old PHP. Sorry I can't help you with Smarty.

Tim

ergophobe

8:11 pm on Mar 4, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



Any Smarty fans care to explain what you like about it, totally apart from answering the original question?