Smartyのblockプラグインで変数を使う方法

  • block系のプラグインで変数を利用するためのプラグインの作成方法です。
  • やりたいことはsectionやforeachを利用せずに配列数に合わせてループとプラス・アルファの処理をさせたいということ。

サンプルソース

実行用のPHP
<?php
require_once 'Smarty.class.php';

$smarty = new Smarty();

$smarty->assign('array', array(
   array('foo'=>'foo1', 'bar'=>'bar1'),
   array('foo'=>'foo2', 'bar'=>'bar2')
));

$smarty->display('test.html');
テンプレート(test.html)
<{sample item=$array}>
    <{$item.foo}> -> <{$item.bar}>
<{/sample}>
block.sample.php
<?php
function smarty_block_sample($params, $content, &$smarty, &$repeat)
{
  if(is_null($content)) {
    $smarty->__temp__ = $params['item'];
    $item = array_shift($smarty->__temp__);
    $smarty->assign('item', $item);
    return;
  }

  $item = array_shift($smarty->__temp__);
  if(is_array($item))
  {
    $smarty->assign('item', $item);
    $repeat = true;
  }
  else
  {
    $repeat = false;
  }
  return $content;
}

$repeatが参照渡しになっているのがポイントですね。

ToDo

  • itemの値を上書きしているので一時的な変数に入れて元に戻す。
  • 分岐処理を精査すれば $smarty->assignを1箇所で済ませるかも?

雑感

久しぶりにSmarty触った。今は2系はバグフィックス程度(2009年最期)で、3系が開発されているんですね。