セクションの指定

広告

設定ファイルに記述された変数は設定ファイルを読み込むだけで利用可能となるグローバル変数と、読み込む範囲を指定した場合だけ読み込まれるセクション変数があります。今までのサンプルで記述していた変数はグローバル変数です。

まずは設定ファイル内にセクションを設定する記述方法から見てください。

変数名 = "値"
変数名 = "値"

[セクション名]
変数名 = "値"
変数名 = "値"

[セクション名]
変数名 = "値"
変数名 = "値"

セクションは設定ファイル内で「[」と「]」で囲んで記述します。セクションは1つの設定ファイル内で複数記述することが出来ます。

url = "www.hogehoge.hoge"
title = "PHP Page"

[Smarty]
title = "Smarty Page"

[Pear]
title = "Pear Page"

設定ファイルの先頭から最初のセクションが現れるまでに記述された変数がグローバル変数となります。グローバル変数は設定ファイルを読み込むだけで参照が可能です。

セクションが記述された以降(次のセクションが現れるまで)に記述された変数はセクション変数となります。セクション変数は設定ファイルを読み込む時にセクションを指定した場合だけ参照が可能となります。

セクション変数とグローバル変数に同じ変数が含まれていた場合はセクション変数が有効となります。

セクションを指定した設定ファイルの読み込み

指定のセクションを含めて設定ファイルを読み込むには、{config_load} 関数を呼びだす時に「section」属性を追加します。

{config_load file="設定ファイル名" section="セクション名"}

例えば「sample.config」ファイルを「Pear」セクションを指定して読み込む場合は次のように記述します。

{config_load file="sample.config" section="Pear"}

サンプルプログラム

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

sample4-1.php

<?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->display('sample4-1.tpl');

?>

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

sample4-1.tpl

{* Smarty config/sample4-1.tpl *}

{config_load file="sample4-1.config" section="Smarty"}

<html>
<head>
<title>Smarty Test</title>
</head>
<body>

<h1>{#title#}</h1>
<p>Site : {#url#}</p>

</body>
</html>

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

sample4-1.config

# 設定ファイル
url = "www.hogehoge.hoge"
title = "PHP Page"

[Smarty]
title = "Smarty Page"

[Pear]
title = "Pear Page"

上記を「sample4-1.config」の名前で「D:¥smartysample¥config¥configs」に保存します。

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

セクションの指定

今回はセクション「Smarty」を指定して読み込んでいる為、変数「title」に「Smarty Page」が設定されてテンプレートファイルに設定ファイルが読み込まれています。

( Written by Tatsuo Ikura )