Re: [SMARTY] Looping Nested Ordered Lists
| From: | messju mohr | Date: | Mon, 24 Nov 2003 08:24:08 +0000 |
| Subject: | Re: [SMARTY] Looping Nested Ordered Lists | ||
| References: | 1 | Groups: | php.smarty.general |
| Request: | Send a blank email to php-smarty-general+get-10594@lists.php.net to get a copy of this message | ||
On Mon, Nov 24, 2003 at 02:15:26AM +1100, Tim Lucas wrote:
> I have a array named $comments available in the template with keys
> 'text' and 'level'
>
> For example:
>
> $comment[0] = ( 'level' => 0, 'text' => 'comment 1' )
> $comment[1] = ( 'level' => 0, 'text' => 'comment 2' )
> $comment[2] = ( 'level' => 1, 'text' => 'in reply to comment
> 2' )
> $comment[3] = ( 'level' => 2, 'text' => 'again in reply to
> comment 2' )
> $comment[4] = ( 'level' => 3, 'text' => 'nested even
> deeper' )
> $comment[5] = ( 'level' => 0, 'text' => 'comment 3' )
>
> how do I do my foreach to create the following:
>
> <ul>
> <li>comment 1</li>
> <li>comment 2
> <ul>
> <li>in reply to comment 2</li>
> <li>again in reply to comment 2
> <ul>
> <li>nest even deeper</li>
> </ul>
> </li>
> </ul>
> </li>
> <li>comment 3</li>
> </ul>
>
> to give the following:
>
> * comment 1
> * comment 2
> o in reply to comment 2
> o again in reply to comment 2
> + nest even deeper
> * comment 3
>
>
> I just can't figure out how to arrange the tags so it works properly.
{assign var=last_level value=0}
{foreach from=$comment item=reply}
{assign var=current_level value=$reply.level+1}
{section name=ul start=$current_level loop=$last_level}</ul>{/section}
{section name=ul start=$last_level loop=$current_level}<ul>{/section}
<li>{$reply.text}</li>
{assign var=last_level value=$current_level}
{/foreach}
{section name=ul start=0 loop=$last_level}</ul>{/section}
"value=$reply.level+1" only works in 2.6.0, use {math} if you want it
portable to older versions.
the sections can be replaced be a modifier that wraps str_repeat. i
did one recently:
<?php
/**
* Smarty repeat modifier plugin
*
* Type: modifier<br>
* Name: repeat<br>
* Date: Nov 21, 2003
* Purpose: repeat a string a number of times
* Input: repeat-count and (optional) delimiter
* Example: {$var|repeat:$times}
* @author messju mohr <messju@lammfellpuschen.de>
* @version 0.2
* @param string
* @param integer
* @param null or string
* @return string
*/
function smarty_modifier_repeat($string, $count, $delim=null)
{
if ($count>0) {
if (isset($delim)) {
return $string . str_repeat($delim . $string, $count-1);
} else {
return str_repeat($string, $count);
}
} else {
return '';
}
}
/* vim: set expandtab: */
?>
this makes the above go:
{assign var=last_level value=-1}
{foreach from=$comment item=reply}
{"</ul>"|repeat:$last_level-$reply.level}
{"<ul>"|repeat:$reply.level-$last_level}
<li>{$reply.text}</li>
{assign var=last_level value=$reply.level}
{/foreach}
{"</ul>"|repeat:$last_level+1}
HTH
messju
> Thanks,
> Tim