phpのsmarty
smarty。。
名前は、かっこいいね。
【参考サイト】
Smarty入門者のための逆引きSmartyリファレンス - 肉とビールとパンケーキ by @sotarok
まず、
http://www.smarty.net/download.php
よりsmarty本体をDLし、解凍し、フォルダごと、c:\php\ 配下にsmartyと名前を代えて設置。
※実際には、libsフォルダのみでよいみたいだけど・・・。
・とりあえず、demo配下のindex.phpにアクセスしてみるが、失敗。ので、defineや、require_onceを変更したら、うまく表示できました。
<?php define('SMARTY_DIR', 'C:/php/smarty/libs/'); require_once(SMARTY_DIR . 'Smarty.class.php'); :: ::
php側で変数に値を設定し、テンプレートファイルで参照
php側
<?php : $vvar = "Hello World!!"; //tplファイル内で"hello"が使用できる。 $smarty->assign('hello', $vvar);
テンプレートファイル
{$hello}
テンプレートファイル側でif文
php側
<?php //if文に使用する変数を宣言 $ifvar = 445; $smarty->assign('num',$ifvar);
テンプレートファイル(50以上100未満:フォント大で赤、100以上:フォント小で青、50未満:フォント小で緑)
{* if文 *} {if $num >= 50 && $num < 100} <font size="5" color="red">{$num}</font> {elseif $num >= 100} <font size="2" color="blue">{$num}</font> {else} <font size="2" color="green">{$num}</font> {/if}
テンプレートファイル側でforeach文
php側
<?php //配列を渡す $data = array("John","Smith","山田","jo-ji"); //$data = array(); $smarty->assign('arr',$data);
テンプレートファイル
{* foreach文 *} <ul> {foreach from=$arr item=val} <li>{$val}</li> {foreachelse} <li>なにもありません</li> {/foreach} </ul>
修飾子
修飾子 - Smarty - PHPphp側
<?php //修飾子 $br = "テスト改行\nTEST..\n"; $smarty->assign('bbr',$br); $tag = "<p>ESCAPE文字</p>"; $smarty->assign('tab',$tag);
テンプレートファイル
{* 修飾子 *} {* \nを認識して<br>に変換してくれる。 *} {$bbr|nl2br} {* <,>,',", を認識してエスケープしてくれる。 *} {$tab|escape:"html"} {* $smarty.nowは、タイムスタンプの形式なので、表示形式を指定して表示する。 *} <p>{$smarty.now|date_format:"%Y/%m/%d %T"}</p>