Smartyを使って、条件分岐(if)で表示を変える
Smartyを使う
SmartyではPHPなどと同じく、if 文で
「○○だったらA」
「○○だったらA、そうでなければB」
というようにHTMLに埋め込んで表示を変更することができます。
使い方は、Smartyを使うと同じ例でいくと
<構成>
test.php
|
|-templatesディレクトリ
| |-temlate.html
|
|-templates_cディレクトリ
・test.php
<?php
require_once('Smarty/libs/Smarty.class.php');
$smarty=new Smarty();
$template_dir='./templates';
$compile_dir='./templates_c';
$animal="Buta";
$smarty->assign("animal",$animal);
$smarty->display("template.html");
?>
・template.html
<html>
{if $animal=="Buta"}これは豚です。{/if}
(解説…変数 $animal がButaの場合、「これは豚です。」と表示させる。)
</html>
ブラウザからtest.phpにアクセスすると、次のようなHTMLページが表示されるはずです。
<html> これは豚です。 </html>
さらにtest.phpで$animal=”Buta”でない場合、「これは豚でない」と表示させる場合
・template.html
<html>
{if $animal=="Buta"}これは豚です。
{else}
これは豚ではありません{/if}
(解説…変数 $animal がButaの場合、「これは豚です。」と表示、そうでなければ「これは豚ではありません」と表示。)
</html>
{if …}
で始まる文は必ず{/if}で終わるようにしないとエラーが出ます。
Smaryマニュアル
http://www.smarty.net/manual/ja/language.function.if.php
