ひとり勉強ログ

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

今さらSmartyの入門vol.2~Hello Worldを表示~

Smartyphpファイル及びテンプレートファイルを作成し、「Hello World」を表示させます。

phpファイル

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

[php] <?php

// ルートディレクトリを設定 define("ROOT_DIR", DIR . "/"); // 関連ファイルを設置するディレクトリ define("PHP_LIBS_DIR", ROOT_DIR . "../php_libs/"); // Smarty本体を設置するディレクトリ define("SMARTY_DIR", _ROOT_DIR . "../../frameworks/smarty/libs/");

// Smartyのテンプレートファイルを保存したディレクトリ define("SMARTY_TEMPLATES_DIR", PHP_LIBS_DIR . "smarty/templates/"); define("SMARTY_TEMPLATES_C_DIR", PHP_LIBS_DIR . "smarty/templates_c/"); define("SMARTY_CONFIG_DIR", PHP_LIBS_DIR . "smarty/configs/"); define("SMARTY_CACHE_DIR", PHP_LIBS_DIR . "smarty/cache/");

require_once (_SMARTY_DIR . "Smarty.class.php");

// Smartyクラスをインスタンス化 $smarty = new Smarty();

// Smartyオブジェクトの設定 // テンプレートの格納先 $smarty->template_dir = SMARTY_TEMPLATES_DIR; // コンパイル済みのテンプレートの格納先 $smarty->compile_dir = SMARTY_TEMPLATES_C_DIR; // 設定ファイルの格納先 $smarty->config_dir = SMARTY_CONFIG_DIR; // キャッシュの格納先 $smarty->cache_dir = SMARTY_CACHE_DIR;

// テンプレート変数のセット $smarty->assign("testvar", "world"); // テンプレートの呼び出し $smarty->display("hello.tpl"); [/php]

テンプレートファイル

特に決まりはありませんが、一般的に拡張子は「.tpl」としていることが多い。 上記phpファイル表示用の「hello.tpl」を「/php_libs/smarty/templates/」に作成する。

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

[php] <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>テスト</title> </head> <body> Hello {$testvar}! </body> </html> [/php]