条件式が偽の時の処理{else}

広告

{if}関数は記述した条件式が真の時に行う処理を記述しましたが、{else}を使うことで偽の場合に行う処理を記述することもできます。書式は次の通りです。

{if 条件式}
  条件式が真(true)の時に実行される処理
{else}
  条件式が偽(false)の時に実行される処理
{/if}

{else}は{if}関数の{if}と{/if}の間に記述して使い条件式が偽(false)だった場合に行う処理を記述します。

具体的には次のように記述します。

{if $engine == 'yahoo'}
  <p>検索サイトは<a href="http://www.yahoo.co.jp/">Yahoo</a>です</p>
{else}
  <p>検索サイトは<a href="http://www.google.co.jp/">Google</a>です</p>
{/if}

上記の場合は変数「engine」に渡されてきた値が「yahoo」だった場合とそうでなかった場合で出力する内容を分けています。

サンプルプログラム

では簡単なサンプルプログラムを作成して試してみます。

sample3-1.php

<?php

require_once('Smarty.class.php');

$smarty = new Smarty();

$smarty->template_dir = 'd:/smartysample/if/templates/';
$smarty->compile_dir  = 'd:/smartysample/if/templates_c/';
$smarty->config_dir   = 'd:/smartysample/if/configs/';
$smarty->cache_dir    = 'd:/smartysample/if/cache/';

$smarty->assign('title', '条件分岐のテスト');
$smarty->assign('engine', 'google');

$smarty->display('sample3-1.tpl');

?>

上記を「sample3-1.php」の名前で「(Apacheドキュメントルート)¥smarty¥if」に保存します。

sample3-1.tpl

{* Smarty if/sample3-1.tpl *}
<html>
<head>
<title>Smarty Test</title>
</head>
<body>

<h1>{$title}</h1>
<p>検索エンジンをお知らせします。</p>
{if $engine == 'yahoo'}
  <p>検索サイトは<a href="http://www.yahoo.co.jp/">Yahoo</a>です</p>
{else}
  <p>検索サイトは<a href="http://www.google.co.jp/">Google</a>です</p>
{/if}

</body>
</html>

上記を「sample3-1.tpl」の名前で「D:¥smartysample¥if¥templates」に保存します。

そしてブラウザから「http://localhost/smarty/if/sample3-1.php」へアクセスして下さい。

条件式が偽の時の処理{else}

( Written by Tatsuo Ikura )