Re: [SMARTY-DEV] enhanced foreach loops
| From: | boots | Date: | Thu, 16 Nov 2006 21:09:03 +0000 |
| Subject: | Re: [SMARTY-DEV] enhanced foreach loops | ||
| References: | 1 | Groups: | php.smarty.dev |
| Request: | Send a blank email to php-smarty-dev+get-2914@lists.php.net to get a copy of this message | ||
Kerry Wilson <kwilson@wmsco.com> wrote: Kerry Wilson wrote:
> I would like to enhance the foreach loop by adding next and previous
> to the foreach variables.
>
> Example usage:
>
> {foreach from=$message.backtrace item='call' name='backtrace'}
> {assign var='previous_call' value=|$smarty.foreach.backtrace.next}|
>
{$call.file} [{$call.line}] -
> {$previous_call.class}.{$previous_call.function}(){/if}
> {/foreach}
>
> In case you cannot tell I am using this to print a backtrace ( I want
> it to show the method it is currently in, not the one that it is
> calling ).
>
> Where does the foreach implementation reside in source? And is this a
> good thing to add to the base code?
>
Here is the code for the feature enhancement, it goes in
Smarty_Compiler.class.php around line 1185.
$output .= "if ({$foreach_props}['total'] > 0):\n";
$output .= " \$_values = array_values(\$_from);\n";
$output .= " foreach (\$_from as
$key_part\$this->_tpl_vars['$item']):\n";
$output .= " if( isset(
\$_values[{$foreach_props}['iteration']-1] ) ) {
{$foreach_props}['prev'] = \$_values[{$foreach_props}['iteration']-1]; }
else { {$foreach_props}['prev'] = false; }\n";
$output .= " if( isset(
\$_values[{$foreach_props}['iteration']+1] ) ) {
{$foreach_props}['next'] = \$_values[{$foreach_props}['iteration']+1]; }
else { {$foreach_props}['next'] = false; }\n";
$output .= " {$foreach_props}['iteration']++;\n";
It actually turned out to be cleaner than I expected. It would be great
if this were added to the next release so my code doesn't break when I
upgrade!
kw
Unfortunately, array_values() has memory implications and possibly severe performance implications
for PHP5 iterator implementing objects; otherwise a nice solution, but I still think you should
implement as a plugin. Maybe consider a compiler plugin for this one.
boots
---------------------------------
Sponsored Link
Mortgage rates near 39yr lows. $510,000 Mortgage for $1,698/mo - Calculate new house payment