0

それ以外の:

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

このようなことをする方法はありますか?

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

これは次のように出力できます。

アイテム-最初のアイテム-最後

行が1つしかない場合は、上記の両方を出力する必要があると思いますか?

4

1 に答える 1

2

ループの外側で条件を記述し、@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たとえば)を作成できます。

于 2012-11-14T19:00:10.517 に答える