- 1. 最小限の設定
- 2. テンプレート変数の記述と展開
- 3. コメント
- 4. {} を表示するには
- 5. テンプレートのインクルード
1. 最小限の設定
最小限の設定として、前ページのディレクトリ構成ができましたらば、下記の構成で
.
|-- cache
|-- configs
|-- index.php
|-- MySmarty.php
|-- templates
| `-- index.tpl
`-- templates_c
index.php、MySmarty.php、index.tpl を作成します。
index.tpl は、通常の HTML ファイルのままで構いません。
MySmarty.php は、下記のように記述します。
<?php
require_once('Smarty.class.php');
class MySmarty extends Smarty
{
public function __construct ()
{
parent::__construct();
$this->template_dir = "./templates/";
$this->compile_dir = "./templates_c/";
$this->config_dir = "./configs/";
$this->cache_dir = "./cache/";
}
public function __destruct ()
{
}
}
?>
index.php は、下記のように記述します。
<?php
require_once("./MySmarty.php");
$smarty = new MySmarty(); // Smartyのインスタンスを作成
$smarty->display('index.tpl'); // テンプレートを指定し表示
?>
smarty の機能らしい機能はいっさい使っていませんが、ウェブサーバの設定でディレクトリのインデックスで index.php を許可する設定になっていれば index.tpl をくっきり表示します。
2. テンプレート変数の記述と展開
テンプレート変数は .tpl 内に
{$変数名}
という形式で記述します。
PHP で
require_once("./MySmarty.php");
$smarty = new MySmarty(); // Smartyのインスタンスを作成
$smarty->assign('変数名', 値や式や変数);
と記述すれば、tpl を展開する際に、テンプレート変数が変換されて展開されます。
3. コメント
コメントは {* で1つ以上の空白をあけて書き始め、1つ以上の空白をあけて *} で閉じます。
{* これは全部コメントになります *}
HTML のコメントと比べて便利なのが、HTML で
<!-- とやってコメントを書くと -->
ブラウザの表面上は表示されませんが、ブラウザのソース表示機能を使用して、HTML のソースを見ると中に記述してあるのがしっかり見られますが。
smarty テンプレート上の {* *} 内は一切展開されませんので、
4. {} を表示するには
上記、2項による、テンプレート変数・コメントの記述の結果、
{* *}
という文字をブラウザ上に表示させるにはどうするかというと、始まりの { を {ldelim} 終わりの } を {rdelim} と記述します。
{ldelim}* *{rdelim}
と書けば smarty でテンプレートを展開後、{* *} と表示されます。
5. テンプレートのインクルード
テンプレートは基本的に .tpl という拡張子で
コンテンツルート/templates_c/
配下に置くわけですが
コンテンツルート/templates_c/templateA.tpl
コンテンツルート/templates_c/templateB.tpl
コンテンツルート/templates_c/sub/templateC.tpl
という構成になっている場合、templateA.tpl 内に
{include file='templateB.tpl'}
{include file='sub/templateC.tpl'}
と書いてやれば、templateB.tpl、sub/templateC.tpl の中身をまるまる展開することができます。
|
        |