Question

Instead of:

{foreach $rows as $row}
    <li class="item{if $row@first} item-first{elseif $row@last} item-last{/if}">{$row.title}</li>
{/foreach}

Is there a way to do something like this?

{foreach $rows as $row}
    <li class="item item-{$row@position}">{$row.title}</li>
{/foreach}

This could output:

item-first item-last

I guess if there is only 1 row then it would need to output both of the above?

Was it helpful?

Solution

You can try to describe condition outside the loop and use @iteration property. For example:

Inside your PHP file:

$lastIteration = count($rows);
$smarty->assign('classMapping', array(
    1 => 'item-first', // iteration always starts at one
    $lastIteration => 'item-last',
));

Inside your template:

{foreach $rows as $row}
    <li class="item {$classMapping[$row@iteration]}">{$row.title}</li>
{/foreach}

But I think that your code (with if statement) is not so bad.


Update

This is a source code of the Smarty 3 foreach function: http://smarty-php.googlecode.com/svn/trunk/distribution/libs/sysplugins/smarty_internal_compile_foreach.php

Look at the class Smarty_Internal_Compile_Foreach and at the method complile() (here is a "shortened" version of this method, which describes how it uses @first modifier):

public function compile($args, $compiler, $parameter)
{                
    $ItemVarName = '$' . trim($item, '\'"') . '@';

    // evaluates which Smarty variables and properties have to be computed
    if ($has_name) {
        $usesSmartyFirst = strpos($tpl->source->content, $SmartyVarName . 'first') !== false;                        
    } else {
        $usesSmartyFirst = false;            
    }        

    $usesPropFirst = $usesSmartyFirst || strpos($tpl->source->content, $ItemVarName . 'first') !== false;

    return $output; // output - is a result of the compilation process
}

So you can create your own internal foreach modifier (@position, for example) only after changing Smarty core classes.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top