PHPのテンプレートエンジン「Smarty」

独習PHPで「Smarty」の使い方を軽く勉強したので軽くメモ。とりあえずインストールの仕方と最小限のページ。

Smarty」のインストール

debian (sid)でのインストールはとても簡単でした。aptで一発。

# apt-get install smarty

これでインストールされます。

基本的な使い方

基本的な使い方です。まず最初に必要なフォルダを用意する必要があります。Smartyを動かすアプリケーションの入っているフォルダに、3つのフォルダを作成します。

# mkdir cache
# mkdir templates
# mkdir templates_c

その後、実際にコードを動かすコードを含むファイルとテンプレートを書いたファイルを作成します。

まず、実際にコードを動かすファイルはこんな感じ。

# vi testSmarty.php
<?php
require_once('smarty/libs/Smarty.class.php');
$o_smarty=new Smarty();
$o_smarty->template_dir='./templates/';
$o_smarty->compile_dir='./templates_c/';
$o_smarty->assign('name','Smarty');
$o_smarty->display('testSmarty.tpl');
?>

続いて、テンプレートを書いたファイルはこんな感じ。さっき作ったtemplatesフォルダいかに作ります。
>|php|# vi templates/testSmarty.tpl


Test <a class="keyword" href="http://d.hatena.ne.jp/keyword/Smarty">Smarty</a>


Test {name}


|

これでブラウザから「http://localhost/testSmarty.php」にアクセスすれば無事ページが表示されるはずです。