ループの外側で条件を記述し、@iterationプロパティを使用することができます。例えば:
PHPファイル内:
$lastIteration = count($rows);
$smarty->assign('classMapping', array(
1 => 'item-first', // iteration always starts at one
$lastIteration => 'item-last',
));
テンプレート内:
{foreach $rows as $row}
<li class="item {$classMapping[$row@iteration]}">{$row.title}</li>
{/foreach}
しかし、あなたのコード(if
ステートメント付き)はそれほど悪くはないと思います。
アップデート
これはSmarty3foreach
関数のソースコードです:http ://smarty-php.googlecode.com/svn/trunk/distribution/libs/sysplugins/smarty_internal_compile_foreach.php
クラスSmarty_Internal_Compile_Foreach
とメソッドを見てください(これは、このメソッドの「短縮」バージョンであり、修飾子complile()
の使用方法を説明しています)。@first
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
}
foreach
したがって、Smartyコアクラスを変更した後でのみ、独自の内部修飾子(@position
たとえば)を作成できます。