|
|
|
|

|
Home ニュース Linux情報 SmartyをFedoraで使う
|
|
作者 kiyoeri
|
|
2009/03/31 火曜日 17:08:48 JST |
Smarty、Fedora、Linux
PostgreSQLを動かすPHPを使用したサンプルで、Smartyを使う機会があったのでそのおさらい。
参考サイト:http://www.gadgety.net/shin/tips/unix/php-tmpl.html Smartyマニュアル:http://www.phppro.jp/phpmanual/smarty/index.html
■Smartyとは ・Xoops、楽天でも使用している。 ・テンプレートエンジン ・MVC(Model View Control)アーキテクチャー ・ロジックとデザインを分離できる。

■現在のFedora9環境 ・既に、Smartyはインストールしてある。 # locate Smarty.class.php /usr/share/php/Smarty/Smarty.class.php
/usr/share/php/Smartyフォルダがある。 phpに組み込まれているかどうかのチェック
# vi smarty.php [smarty.php]
<?php require_once("Smarty/Smarty.class.php"); $smary = new Smarty; echo "インストールしたSmartyのVersionは{$smary->_version}です"; ?> |
# php smarty.php インストールしたSmartyのVersionは2.6.20です。
■Smartyの入手とインストール ・主要Linuxのディレウトリビューションでは、パッケージマネージャでインストールできる。 Fedora9の場合は、以下のような構成
/usr/share/php/Smarty ├ Config_File.class.php Smarty.class.php Smarty_Compiler.class.php debug.tpl └ Smarty_Compiler.class.php.security~ plugins/ internals/
・最新版はSmartyの本家サイト(http://www.smarty.net/download.php ) より入手する。 $ wget http://www.smarty.net/do_download.php?download_file=Smarty-2.6.22.tar.gz $ tar xzvf Smarty-2.6.22.tar.gz
Smarty-2.6.22 ├ BUGS COPYING.lib ChangeLog FAQ INSTALL NEWS QUICK_START README RELEASE_NOTES ├ TODO/ demo/ misc/ unit_test/ └ libs ←※このlibsフォルダがSmartyのインストール単位 ├ Config_File.class.php Smarty.class.php Smarty_Compiler.class.php debug.tpl └ internals/ plugins/
※インストール場所は、インストール場所は、「Smarty.class.php」がrequire_once等で 読み込めればどこでも可
・インストール有無の確認 smarty.phpを動作させて確認する。
■Smartyの使い方 ・デイレクトリ構成
├ Smarty ┰ Smarty.class.php │ └ Internals/ plugins/ ├ templates - index.tpl ├ templates_c ├ configs ├ cache └ index.php
| templates | テンプレートファイルを格納するディレクトリ。各テンプレートファイルの拡張子は .tpl。 | | templates_c | テンプレートファイルを利用して php ファイルに展開されたファイルを格納するキャッシュ用ディレクトリ。Webサーバー(httpd)がファイルを作成するので、httpd.conf で設定されている Webサーバーを起動するアカウント(User, Group)が書き込みできるオーナーとパーミッションにしなければならない。 例) chown nobody:nobody templates_c chmod 770 templates_c | | configs | テンプレートなどを利用する際の設定や初期値などを登録するファイルを格納するディレクトリ。 設定ファイルが test.conf という名前の場合、テンプレートファイル内で以下のように利用する。 --- test.conf ------------------------------ # global pageTitle = "Mail Page" bodyBgColor = "#FFFFFF"
[Sub] pageTitle = "Sub Page" ---------------------------------------------
--- template for main --------------------- {config_load file="test.conf"}
<html> <title>{#pageTitle#}</title> <body bgcolor="{#bodyBgColor#}"> ... ---------------------------------------------
--- template for sub ---------------------- {config_load file="test.conf" section="Sub"}
<html> <title>{#pageTitle#}</title> <body bgcolor="{#bodyBgColor#}"> ... --------------------------------------------- | | cache | built-in caching という機能を有効($smarty->caching = true;)にした際に使用されるキャッシュ用ディレクトリ。Webサーバー(httpd)がファイルを作成するので、httpd.conf で設定されている Webサーバーを起動するアカウント(User, Group)が書き込みできるオーナーとパーミッションにする。 例) chown nobody:nobody cache chmod 770 cache |
・index.phpの作成
①Smartyのインスタンスを作成する。
require_once("Smarty/Smarty.class.php"); $smarty = new Smarty;
/*どうしても、 Smarty.class.php が No such file or directory となる場合、*/ /*この場合は、Smartyフォルダは不要*/ define('SMARTY_DIR','/usr/share/php/Smarty/'); require_once(SMARTY_DIR.'Smarty.class.php'); $smarty = new Smarty;
/*Smartyは、Smarty.class.phpファイルさえ見つけられれば利用可能になるので*/ /*libs ディレクトリ内の構成を変更せずに適当なディレクトリにライブラリを置き、 */ /*フルパスで指定しても動作する。*/ require_once('/usr/share/php/Smarty/Smarty.class.php'); $smarty = new Smarty;
②テンプレート、テンプレートキャッシュ、設定、サーバーキャッシュを設定 //Smartyの設定 $smarty->caching = true; $smarty->compile_check = false;
$smarty->template_dir = 'templates'; $smarty->compile_dir = 'templates_c/'; $smarty->config_dir = 'configs'; $smarty->cache_dir = 'cache';
$smarty->assign('name', 'Kiyoeri'); $smarty->assign('url', 'http://www.my-domain.com/'); ←※開始URL
$smarty->display('index.tpl');
・index.tplの作成 <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>User Info</title> </head> <body> <p>ユーザー情報:</p> 名前:{$name}<br> URL: <a href="{$url}">{$url}</a><br> 日付:{$smarty.now|date_format:"%Y年%m月%d日"}<br> </body> </html>
■テンプレートの文法 ・全てのテンプレートタグはデリミタによって囲まれる。 ・デフォルトではデリミタは { と } ですが、これは 変更可能。
・構文
| 項目 | 構文 | 説明 | | コメント | {* これはコメントです *} | アスタリスクで囲まれる部分がコメント Smarty コメントはブラウザへは送信されない。 | | 変数 | {$foo} | 単純な変数 (配列やオブジェクト以外) を表示 | | {$foo[4]} | 0から始まるインデックスを持った配列の5番目の要素 | | {$foo.bar} | "bar"というキーに対応する配列の値 | | {$foo.$bar} | 変数のキーに対応する配列の値 | | {$foo->bar} | オブジェクト$fooのプロパティ "bar"を表示 | | {$foo->bar()} | オブジェクト$fooのメソッド"bar"の返り値 | | {#foo#} | configファイル変数"foo"を表示 | | {$smarty.config.foo} | {#foo#}と同じ。 | | {$foo[bar]} | sectionループ内でのみ正当な構文 | | 関数・属性 | {funcname attr1='val1' attr2='val2'} | 関数名とその属性値を記述する。 複数の属性値の区切り文字は半角スペース。 | | {func var="test $foo test"} | $foo を参照 | | {func var="test $foo_bar test"} | $foo_bar を参照 | | {func var="test $foo[0] test"} | $foo[0] を参照 | | {func var="test $foo[bar] test"} | $foo[bar] を参照 | | {func var="test $foo.bar test"} | $foo (not $foo.bar) を参照 | | {func var="test `$foo.bar` test"} | $foo.bar を参照 | | {func var="test `$foo.bar` test"|escape} | 修飾子はクォートの外で! | | 演算子 | {$foo+1} | 加算 | | {$foo-$bar} | 減算 | | {$foo*$bar} | 乗算 | | {$foo/$bar} | 除算 |
・変数 ①PHP から 割り当てられた変数は、 (php と同様に) 先頭にドル記号 ($ ) をつける事で参照できる。 [*.php] <?php $smarty = new Smarty(); $smarty->assign('firstname', 'Doug'); $smarty->assign('lastname', 'Evans'); $smarty->assign('meetingPlace', 'New York'); $smarty->display('index.tpl'); ?>
一方、[*.tpl] の内容はこのようになる。 Hello {$firstname} {$lastname}, glad to see you can make it.
<br />
{* これは動作しません。変数名は大文字小文字を区別するからです。 *}
This weeks meeting is in {$meetingplace}.
{* こちらは動作します *}
This weeks meeting is in {$meetingPlace}. |
②PHP から割り当てられた連想配列を参照することもできる。 この場合は、'.' (ピリオド) 記号の 後にキーを指定する。 [*.php] <?php $smarty->assign('Contacts', array('fax' => '555-222-9876', 'email' => '
このメールアドレスはスパムボットから保護されています。観覧するにはJavaScriptを有効にして下さい
', 'phone' => array('home' => '555-444-3333', 'cell' => '555-111-1234') ) ); $smarty->display('index.tpl'); ?>
一方、[*.tpl] の内容はこのようになる。
{$Contacts.fax}<br /> {$Contacts.email}<br /> {* you can print arrays of arrays as well *} {$Contacts.phone.home}<br /> {$Contacts.phone.cell}<br /> |
③配列に対してインデックスでアクセスすることもできる。 [*.php] <?php $smarty->assign('Contacts', array( '555-222-9876', '
このメールアドレスはスパムボットから保護されています。観覧するにはJavaScriptを有効にして下さい
', array('555-444-3333', '555-111-1234') )); $smarty->display('index.tpl'); ?>
一方、[*.tpl] の内容はこのようになる。 {$Contacts[0]}<br />
{$Contacts[1]}<br />
{* you can print arrays of arrays as well *}
{$Contacts[2][0]}<br />
{$Contacts[2][1]}<br /> |
④PHP から割り当てられた オブジェクトのプロパティにアクセスするには、 -> 記号の後にプロパティ名を指定する。
name: {$person->name}<br />
email: {$person->email}<br /> |
⑤設定ファイルから読み込まれた変数を参照するには、それをハッシュマーク (# ) で囲むか、 あるいは Smarty 変数$smarty.configを使用する。 後者は、クォートされた属性値の中に含める 場合に便利。
サンプルの設定ファイル - foo.conf : pageTitle = "This is mine"
bodyBgColor = '#eeeeee'
tableBorderSize = 3
tableBgColor = "#bbbbbb"
rowBgColor = "#cccccc" |
#hash# 方式のテンプレート {config_load file='foo.conf'}
<html>
<title>{#pageTitle#}</title>
<body bgcolor="{#bodyBgColor#}">
<table border="{#tableBorderSize#}" bgcolor="{#tableBgColor#}">
<tr bgcolor="{#rowBgColor#}">
<td>First</td>
<td>Last</td>
<td>Address</td>
</tr>
</table>
</body>
</html> |
$smarty.config方式のテンプレート
{config_load file='foo.conf'}
<html>
<title>{$smarty.config.pageTitle}</title>
<body bgcolor="{$smarty.config.bodyBgColor}">
<table border="{$smarty.config.tableBorderSize}" bgcolor="{$smarty.config.tableBgColor}">
<tr bgcolor="{$smarty.config.rowBgColor}">
<td>First</td>
<td>Last</td>
<td>Address</td>
</tr>
</table>
</body>
</html> |
どちらの場合も出力は同じ。
・予約変数 PHP の予約変数 {$smarty} を使用すると、環境変数やリクエスト変数にアクセスすることができる。 ①リクエスト変数へのアクセス $_GET 、$_POST 、 $_COOKIE 、$_SERVER 、 $_ENV および $_SESSION
リクエスト変数の表示 {* ($_GET) http://www.example.com/index.php?page=foo から page の内容を表示 *}
{$smarty.get.page}
{* ($_POST['page']) フォームから送信された変数"page"の値を表示 *}
{$smarty.post.page}
{* クッキーに登録された"username"の値を表示 ($_COOKIE['username']) *}
{$smarty.cookies.username}
{* サーバ変数"SERVER_NAME"の値を表示 ($_SERVER['SERVER_NAME']) *}
{$smarty.server.SERVER_NAME}
{* 環境変数"PATH"の値を表示 *}
{$smarty.env.PATH}
{* phpのセッション変数"id"の値を表示 ($_SESSION['id']) *}
{$smarty.session.id}
{* get/post/cookies/server/envの値から、変数"username"の値を表示 *}
{$smarty.request.username} |
注意: 歴史的な理由から、{$SCRIPT_NAME} には直接アクセスできる。しかし、この値にアクセスする 方法としては {$smarty.server.SCRIPT_NAME} が推奨されている。
<a href="{$SCRIPT_NAME}?page=smarty">click me</a>
<a href="{$smarty.server.SCRIPT_NAME}?page=smarty">click me</a> |
②現在のタイムスタンプにアクセスするには {$smarty.now} を使用する。
{* date_format 修飾子を用いて、現在の日付と時刻を表示します *} {$smarty.now|date_format:'%Y-%m-%d %H:%M:%S'} |
③PHP 定数の値に直接アクセスするには{$smarty.const}を使用する。
<?php // php で定義されている定数 define('MY_CONST_VAL','CHERRIES'); ?> |
定数を出力するテンプレート
④その他 ・{$smarty.capture}
{$smarty.config} 変数は、読み込まれた config 変数 を参照するのに使用できる。 {$smarty.config.foo} は {#foo#} と同義。詳細: {config_load}
・{$smarty.section}、{$smarty.foreach} {$smarty.section} 変数および {$smarty.foreach} 変数は、 {section} および {foreach} のループプロパティを参照するために使用する。 この中には .first 、.index といった有用な値が含まれる。
・{$smarty.template} 現在処理中のテンプレートの名前を返す。 次の例の container.tpl と、そこから インクルードしている banner.tpl の両方で {$smarty.template} を使用している。 <b>Main container is {$smarty.template}</b>
{include file='banner.tpl'} |
出力は、このようになる。 <b>Main page is container.tpl</b>
banner.tpl |
・ {$smarty.version}このテンプレートをコンパイルした Smarty のバージョンを返す。 <div id="footer">Powered by Smarty {$smarty.version}</div> |
・ {$smarty.ldelim}、{$smarty.rdelim} |
|
最終更新日 ( 2009/04/01 水曜日 18:58:36 JST )
|
|