Php – the best way to handle recursion in smarty

phprecursionsmartytemplates

I found a couple of ways to handle recursion in Smarty, mostly based on including templates into themselves, which seems like ridiculous waste of resources. I found one solution, by Messju over at Smarty that seemed to be just right – but it is not supported and fails in the latest version of smarty 🙁

For people asking: What I want smarty to print out is a discussion thread that is defined by an array of entries. If an entry has one or more answers, those are listed as children to said entry in an array, and so on.

array(
    array(
        'id'=>0,
        'headline'=>"My parent headline",
        'body'    =>"My parent body",
        'children'=>array(
            array(
                'id'=>1,
                'headline'=>"My firstChild headline",
                'body'    =>"My firstChild body",
                'children'=>array()
            ),
            array(
                'id'=>2,
                'headline'=>"My secondChild headline",
                'body'    =>"My secondChild body",
                'children'=>array()
            )
        )
    ),
);

The nested array has an arbitrary depth, and each entry will have an arbitrary number of children. To me this is something I want to do with within the scope of the template, as I consider it pure display logic. I do not want to have to handle HTML or some type of HTML placeholders outside of the template.

I want smarty to print this as nested lists:

<ul>
    <li>
        <h1>My parent headline</h1>
        <p>My parent body</p>
        <ul>
            <li>
                <h1>My firstChild headline</h1>
                <p>My firstChild body</p>
            </li>
            <li>
                <h1>My secondChild headline</h1>
                <p>My secondChild body</p>
            </li>
        </ul>
    </li>
</ul>

I'm starting to realize this might be a very case-by-case problem, so I figure I'll just write a smarty plugin to handle this specifically, although I'd rather have an all-around solution.

Is there a way?

Best Solution

With Smarty 3, this can be done using {function}. The following code will produce the required ouput.

{function name=printList}
<ul>
    {foreach $items as $item}
    <li>
        <h1>{$item['headline']}</h1>
        <p>{$item['body']}</p>
        {if $item['children']}
            {call name=printList items=$item['children']}
        {/if}
    </li>
    {/foreach}
</ul>
{/function}

{call name=printList items=$comments}

More information can be found at the docs.

Side note: Just because something is complex or recursive it doesn't mean that it can't be inside a template. For God's sake the HTML ul-li structure is naturally recursive and by hiding it away or moving it somewhere else (just because it is too complex for a template) you are introducing an extra complexity into the application.