Smarty 3.1.28にアップグレートしたら、意外なところで問題があったので共有します。
3.1.27 では全く問題なかったのですが、こんなマイナーバージョン・アップで問題が…
問題の部分というのは、generator
をテンプレート変数に assign
した場合に起こりました。
問題を再現するミニマムコードは以下のようになります。
index.php
<?php
require_once '/usr/share/php/Smarty/Smarty.class.php';
$smarty = new Smarty();
$smarty->setTemplateDir('../../templates')
->setCompileDir('../../templates_c')
->addPluginsDir('../../smarty_plugins')
->setCacheDir('../../cache')
->setConfigDir('../../smartyconfigs');
function gen()
{
$arrSample = [
0 => 'a'
, 1 => 'b'
, 2 => 'c'
, 3 => 'd'
];
foreach ($arrSample as $val) {
yield $val;
}
}
$smarty->assign('generator', gen());
$smarty->display('sandbox/index.tpl');
index.tpl
<!DOCTYPE HTML>
<html lang="ja-JP">
<head>
<meta charset="UTF-8">
<meta name="robots" content="NOINDEX,NOFOLLOW" />
<meta http-equiv="content-language" content="ja" />
<meta content='width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no' name='viewport' />
<link rel="icon" href="favicon.ico" />
<link href="/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css" rel="stylesheet" />
<link href="https://code.ionicframework.com/ionicons/2.0.1/css/ionicons.min.css" rel="stylesheet" type="text/css" />
<title></title>
</head>
<body>
<div class="container">
{foreach $generator as $val}
{$val}
{/foreach}
</div>
<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
<script src="https://code.jquery.com/ui/1.11.4/jquery-ui.min.js"></script>
<script src="/js/bootstrap.min.js"></script>
</body>
</html>
再現するエラーはこちら。
テンプレートの展開時にどうもforeach が2回回ってしまう様子…