設定ファイルの読み込みと変数の参照
テンプレートファイルで設定ファイルに記述された変数を参照するには、テンプレートファイル内で設定ファイルを読み込みことが必要です。設定ファイルを読み込むには {config_load} 関数を使います。
{config_load file="設定ファイル名"}
「file」属性に読み込むファイル名を指定します。「file」属性は必須となっています。設定ファイル名は「configs」ディレクトリに含まれている必要があります。例えば次のように記述します。
{config_load file="sample.config"}
テンプレートファイル内で記述する位置に決まりは無いようですが、設定ファイル内の変数を参照するよりも前に {config_load} 関数を呼び出しておく必要があります。
設定ファイルの読み込みと変数の参照
設定ファイル内で記述された変数を参照するには2つの方法があります。1つ目の方法は変数名を「#」で囲み、さらにデリミタである「{」と「}」で囲います。書式としては次のようになります。
{#変数名#}
2つ目の方法はSmartyの予約変数である {$smarty.config} を使います。次の書式にて設定ファイル内の変数を参照できます。
{$smarty.config.変数名}
どちらの方式でも結果は同じになります。変数を参照する前に設定ファイルが読み込まれている必要がある点に注意して下さい。
{config_load file="sample.config"} <html> <head> <title>Smarty Test</title> </head> <body> <p>Site:{#url#}</p> <p>E-Mail:{$smarty.config.mail}</p> </body> </html>
サンプルプログラム
では簡単なサンプルプログラムを作成して試してみます。
<?php require_once('Smarty.class.php'); $smarty = new Smarty(); $smarty->template_dir = 'd:/smartysample/config/templates/'; $smarty->compile_dir = 'd:/smartysample/config/templates_c/'; $smarty->config_dir = 'd:/smartysample/config/configs/'; $smarty->cache_dir = 'd:/smartysample/config/cache/'; $smarty->assign('title', 'Test'); $smarty->display('sample3-1.tpl'); ?>
上記を「sample3-1.php」の名前で「(Apacheドキュメントルート)¥smarty¥config」に保存します。
{* Smarty config/sample3-1.tpl *} {config_load file="sample3-1.config"} <html> <head> <title>Smarty Test</title> </head> <body> <h1>{$title}</h1> <p>Site : {#url#}</p> <p>E-Mail : {$smarty.config.mail}</p> </body> </html>
上記を「sample3-1.tpl」の名前で「D:¥smartysample¥config¥templates」に保存します。
# 設定ファイル url = "www.hogehoge.hoge" mail = 'hoge@hogehoge.hoge'
上記を「sample3-1.config」の名前で「D:¥smartysample¥config¥configs」に保存します。
そしてブラウザから「http://localhost/smarty/config/sample3-1.php」へアクセスして下さい。
( Written by Tatsuo Ikura )