Smartyを使ってみる
久々コーディングを。
Smartyを使うかもなので、ひとまず試してみました。
ライブラリはこちらのdownloadよりダウンロードし、解凍したフォルダの
Smarty-x.x.x/libs
をinclude_pathに含めればまずは準備完了です。
< ?phpこんな感じでPHPファイルを作成し、templatesフォルダ内にtest.tplを
//Smartyライブラリ読み込み
require_once 'Smarty.class.php';
//Smartyのインスタンスを作成
$smarty = new Smarty();
//各ディレクトリの指定
$smarty->template_dir = './templates/';
$smarty->compile_dir = './templates_c/';
$smarty->config_dir = './configs/';
$smarty->cache_dir = './cache/';
smarty->assign('arg1', "test");
//テンプレートを指定し表示
$smarty->display("test.tpl");
?>
<HTML lang="ja">
<HEAD>
<META http-equiv="content-type" content="text/html; charset=UTF-8">
<TITLE>{$arg1|escape}</TITLE>
</HEAD>
<BODY TEXT="black" BGCOLOR="white">
{* テンプレート中のコメント *}
<!-- タイトル -->
<div align="center"><font size="5"><b>{$arg1|escape}</b></font></div>
<hr width="600" align="center">
</BODY>
</HTML>
とすればひとまずOKです。
{$パラメータ}
でassignした文字列が表示でき、escapeのいろいろ方法があってJavaScriptにも適応可能で、確かに使い勝手はよさそうです。
「{}」がコードの対象なので、こちらを表示する際には{’{'}とする必要があります。
また、
$smarty->compile_dir
で指定したディレクトリは実行ユーザー(apacheユーザー)が書き込み可能なフォルダでなければなりませんので、注意が必要です。
Posted in PHP |
