Smarty入門メモ
via
Smarty入門者のための逆引きSmartyリファレンス - 肉とご飯と甘いもの @ sotarok
社内環境で動かしてみたのでとりあえずソースだけメモメモ
HTML側
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <meta http-equiv="content-language" content="ja" /> <meta http-equiv="content-style-type" content="text/css" /> <meta http-equiv="content-script-type" content="text/javascript" /> <title>smartyテスト</title> <script type="text/javascript"> {literal} function hoge() { alert(1); } {/literal} </script> </head> <body> <h1>smartyテスト</h1> <p>変数出力:{$hello}</p> <p>配列出力:{$array.hello}</p> <p>コメントコメント→:{* ここは表示されない *}</p> <p><a href="javascript:void(0);" onclick="hoge(); return false;">{literal}{}{/literal}がデリミタなので、リテラル化する(jsも)</a></p> <div> <h2>if文テスト</h2> {if $is_hello == 1} <p>こんにちは!こんにちは!</p> {elseif $is_hello == 2} <p>おはよう!おはよう!</p> {else} <p>こんばんは!こんばんは!</p> {/if} </div> <div> <h2>配列をすべて出力:foreach</h2> <ul> {foreach from=$alpha key=key item=val } <li>{$key} : {$val}</li> {/foreach} </ul> </div> <div> <h2>配列に値がない場合:foreach</h2> <ul> {foreach from=$aplha2 item=val key=key} <li>{$key} : {$val}</li> {foreachelse} <li>なにもありません</li> {/foreach} </ul> </div> <h2>HTMLをエスケープして表示</h2> <p>{$hello|escape:"html"|nl2br}</p> <h2>日付の表示方法を指定</h2> <p>{$timestamp|date_format:"%Y年%m月%d日 %T"}</p> <h2>変数が空だった場合のデフォルト</h2> <p>{$title|default:"no title"}</p> <h2>循環テーブル(odd, evenのあれ)</h2> <table border="1"> {foreach from=$array_odd item=val} <tr class="{cycle values="odd,even"}"> <td>{$val.title}</td><td>{$val.price}</td> </tr> {/foreach} </table> </body> </html>
PHP側
<?php define ('SMARTY_DIR', '/***/php/smarty/smarty/'); // 設置したSmarty本体へのパスを設定します(絶対パス) require_once 'smarty/Smarty.class.php'; $smarty = new Smarty(); $smarty->template_dir = '/***/php/smarty/templates/'; // 設置したtemplates への絶対パス $smarty->compile_dir = '/***/php/smarty/templates_c/'; // 設置したtemplates_cへの絶対パス // 変数で出力 $data = "Hello <strong> World!!</strong>"; $smarty->assign('hello', $data); // 配列 $array = array( 'hello' => 'world', 'hoge' => 'fuga', ); $smarty->assign('array', $array); // if文 $smarty->assign('is_hello', 2); // foreach $alpha = array(1 => 'a', 2 => 'b', 3 => 'c' ); $smarty->assign('alpha', $alpha); $alpha = array(); $smarty->assign('alpha2', $alpha); // 時間表示方法 $smarty->assign('timestamp', 20080326003305); // 循環表示 // 配列 $array = array( 'hello' => array( 'title' => 'title1', 'price' => '200001' ), 'hello1' => array( 'title' => 'title2', 'price' => '200002' ) ); $smarty->assign('array_odd', $array); // テンプレート出力 ///// $smarty->display('index.tpl'); // こうすることで、templatesディレクトリにある index.tpl を読み込み、出力する ?>