デフォルト値の定義(default)
「default」はテンプレートファイル内で記述された変数に、PHPスクリプト内から値が指定されなかったり、指定された場合でも値が空だった場合に割り当てられるデフォルトの値を指定する場合に使います。書式は次の通りです。
{$変数名|default[:デフォルト値]}
パラメータに指定した値がデフォルトの値となります。パラメータは省略可能ですが省略された場合は空のままです。
具体的には次のように記述します。
名前は {$name|default:"未入力"} です
サンプルプログラム
では簡単なサンプルプログラムを作成して試してみます。
<?php
require_once('Smarty.class.php');
$smarty = new Smarty();
$smarty->template_dir = 'd:/smartysample/modifier/templates/';
$smarty->compile_dir = 'd:/smartysample/modifier/templates_c/';
$smarty->config_dir = 'd:/smartysample/modifier/configs/';
$smarty->cache_dir = 'd:/smartysample/modifier/cache/';
$smarty->assign('title', '修飾子のテスト');
$smarty->assign('address', '');
$smarty->display('sample4-1.tpl');
?>
上記を「sample4-1.php」の名前で「(Apacheドキュメントルート)¥smarty¥modifier」に保存します。
{* Smarty modifier/sample4-1.tpl *}
<html>
<head>
<title>Smarty Test</title>
</head>
<body>
<h1>{$title}</h1>
<p>名前は「{$name}」です</p>
<p>名前は「{$name|default}」です</p>
<p>名前は「{$name|default:"未入力"}」です</p>
<p>住所は「{$address|default:"未入力"}」です</p>
</body>
</html>
上記を「sample4-1.tpl」の名前で「D:¥smartysample¥modifier¥templates」に保存します。
そしてブラウザから「http://localhost/smarty/modifier/sample4-1.php」へアクセスして下さい。
テンプレートに記述した変数にPHPスクリプト側で「assign」メソッドを使った場合でも割り当てられた値が空の場合はデフォルト値が表示されます。
( Written by Tatsuo Ikura )
PHPBook