ひとり勉強ログ

ITエンジニアの勉強したことメモ

今さらSmartyの入門vol.4~変数~

今回は変数に関して。

assignメソッド

「templates」ディレクトリ内に「.tpl」の拡張子で作成したファイルがテンプレートファイル。

テンプレートファイルから参照可能な変数をテンプレート変数という。

assignメソッドを使用して、変数名と値をセットにし、テンプレート変数に割り当てる。

まずファイルの作成。

格納ディレクトリ:/htdocs/直下 ファイル名:variables.php

[php] <?php // Smarty派生クラスを読み込む require_once("./MySmarty.class.php"); // 派生クラスMySmartyをインスタンス化 $smarty = new MySmarty();

// 変数 $smarty->assign("test_variable", "セットされた変数"); [/php]

displayメソッド

変数名と値をセットしたら、displayメソッドで表示させるテンプレートを呼び出す。

[php] // テンプレートの呼び出し $smarty->display("variables.tpl"); [/php]

テンプレートファイルの作成

「variables.tpl」としたので、「/php_libs/smarty/templates/」内に以下のようにテンプレートファイルを作成。

格納ディレクトリ:/php_libs/smarty/templates/ ファイル名:variables.tpl

[html] <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Smartyでの変数の表示</title> </head> <body>

<h1>Smartyでの変数の表示</h1>

<h2>変数</h2> <p>{$test_variable}</p> </body> </html> [/html]

今後、「variables.php」「variables.tpl」にどんどん追記していきます。

単純配列

variables.php [php] // 単純配列 $smarty->assign("lang", array("日本語", "英語", array("北京語", "広東語"))); [/php]

variables.tpl [html] <h2>単純配列</h2> <ul> <li>{$lang[0]}</li> <li>{$lang[1]}</li> <li>{$lang[2][0]}</li> <li>{$lang[2][1]}</li> </ul> [/html]

連想配列

variables.php [php] // 連想配列 $smarty->assign("book", array( "title" => "PHP+MySQLマスターブック", "publish" => "マイナビ", "author" => "永田 順伸", "price" => "2700") ); [/php]

variables.tpl [html] <h2>連想配列</h2> <table border="1"> <tbody> <tr> <th>書籍タイトル</th> <td>{$book.title}</td> </tr> <tr> <th>出版社</th> <td>{$book.publish}</td> </tr> <tr> <th>著者</th> <td>{$book.author}</td> </tr> <tr> <th>価格</th> <td>{$book.price}</td> </tr> </tbody> </table> [/html]

オブジェクト

variables.php [php] // オブジェクト $objectClass = new MyTestClass("長澤まさみ", "19870603"); $smarty->assign("actor", $objectClass);

class MyTestClass { public function construct($name, $birth) { $this->name = $name; $this->birth = $birth; } public $name; public $birth; public function getAge() { return floor*1; [/php]

variables.tpl [html] <h2>複数の変数を同時に割り当てる</h2> <dl> <dt>PERT</dt> <dd>{$PERT}</dd> <dt>WBS</dt> <dd>{$WBS}</dd> <dt>OBS</dt> <dd>{$OBS}</dd> </dl> [/html]

*1:date('Ymd') - $this->birth)/10000); } } [/php]

variables.tpl [html] <h2>オブジェクト</h2> <p>名前:{$actor->name}<br> 誕生日:{$actor->birth}<br> 年齢:{$actor->getAge()}歳</p> [/html]

複数の変数を同時に割り当てる

variables.php [php] // 複数の変数を同時に割り当てる // 変数名と変数値の組をセットして、まとめてテンプレート変数として割り当てる $smarty->assign(array( "PERT" => "Program Evaluation and Review Technique", "WBS" => "Work Breakdown Structure", "OBS" => "Organization Breakdown Structure"