Smarty – 繰り返し処理(foreach)
繰り返し(foreach)
{foreach}
{foreachelse}
{/foreach}
{foreachelse}
{/foreach}
を利用すると、解析時に配列の要素に応じた繰り返し処理を行うことが出来る。
書式
{foreach from=[配列] key=[キー] item=[アイテム] name=[このループブロックの名前]}
// 処理
{foreachelse}
// 処理
{/foreach}
foreachの繰り返し処理では、fromに割り当てられた配列の要素数分だけ自動的に繰り返し処理が実行される。繰り返しのたびに、keyに指定したテンプレート変数に配列へのアクセスキーが、itemに指定したテンプレート変数に配列の中身がそれぞれ割り当てられる。nameには、このループの名前を指定することが出来る。foreachはネストが可能なので、対象ブロックを区別することができる。
{foreachelse}を記述している場合、配列の要素が空の場合にこちらのブロックの処理が実行される。
サンプルコード
foreach.php
<?php
require_once('Smarty/Smarty.class.php');
$smarty = new Smarty;
$smarty->assign("data", array("data1", "data2", "data3"));
$smarty->display('foreach.tpl');
?>
foreach.tpl
<html>
<head>
<title>foreach</title>
</head>
<body>
<ul>
{foreach from=$data key="key" item="value" name="list"}
<li>{$key}:{$value}</li>
{foreachelse}
データがない
{/foreach}
</ul>
</body>
</html>
実行結果
0:data1 1:data2 2:data3
現在のループ回数を取得する
iteration変数を利用する。
{$smarty.foreach.foreachname.iteration}
Smarty – HelloWorld
helloworld
SmartyでHelloWorldを作ってみる。
テンプレートファイル(templates/helloworld.tpl)
<html>
<head>
<title>{$title}</title>
</head>
<body>
{$body}
</body>
</html>
{$xxx}はテンプレート変数であり、プログラムの実行時に動的に値を設定するための構文。
プログラム(helloworld.php)
<?php
require_once('Smarty/Smarty.class.php');
$smarty = new Smarty;
$smarty->assign("title", "sample");
$smarty->assign("body", "helloworld");
$smarty->display('helloworld.tpl');
?>
手順は以下の通り。
- Smartyオブジェクトをインスタンス化する(new Smarty)
- 値を設定する(assign)
- 表示する(display)
実行結果

テンプレートの{$title}{$body}に対してそれぞれ値が設定された。
Smarty – 条件分岐(if)
条件分岐
テンプレート内で条件分岐を行うことが可能。
書式
{if 条件1}
条件1に一致したときの処理
{elseif 条件2}
条件2に一致したときの処理
{else}
上記の条件に一致しなかったときの処理
{/if}
条件に当てはまったブロックが実行される。
利用できる演算子(http://smarty.php.net/manual/en/language.function.if.phpより引用)
| Qualifier | Alternates | Syntax Example | Meaning | PHP Equivalent |
|---|---|---|---|---|
| == | eq | $a eq $b | equals | == |
| != | ne, neq | $a neq $b | not equals | != |
| > | gt | $a gt $b | greater than | > |
| < | lt | $a lt $b | less than | < |
| >= | gte, ge | $a ge $b | greater than or equal | >= |
| <= | lte, le | $a le $b | less than or equal | <= |
| === | $a === 0 | check for identity | === | |
| ! | not | not $a | negation (unary) | ! |
| % | mod | $a mod $b | modulous | % |
| is [not] div by | $a is not div by 4 | divisible by | $a % $b == 0 | |
| is [not] even | $a is not even | [not] an even number (unary) | $a % 2 == 0 | |
| is [not] even by | $a is not even by $b | grouping level [not] even | ($a / $b) % 2 == 0 | |
| is [not] odd | $a is not odd | [not] an odd number (unary) | $a % 2 != 0 | |
| is [not] odd by | $a is not odd by $b | [not] an odd grouping | ($a / $b) % 2 != 0 |

