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.