Smarty 使用例
![]() |
include | 外部モジュール郡 |
| Smarty | テンプレートエンジン | |
| htdocs | コンテンツファイル | |
| cache | Smarty用キャッシュ (出力結果である静的なHTMLファイル) |
|
| templates | テンプレートデザインファイル (Smartyのルールに従ったHTMLファイル) |
|
| templates_c | Smarty用テンプレート解析後のファイル (PHPの構文に置き換えられたPHPファイル) |
|
| cache templates_cのディレクトリはPHPの実行ユーザーから書き込めるように権限を設定します。 chmod a+w template_c |
||
Smartyのプロパティ
| $compile_check | デバッグが無事に済めばfalseに設定します。 |
| $debugging | デバッグ情報の表示設定を切り替えます。 |
| $caching | ここの様な制的コンテンツの場合に有効にします。 カレンダーなど月毎に変更される様なコンテンツにも効果があります。 |
| $template_dir | $compile_checkがfalseになれば必要なくなります。 開発と本番のサーバーが別の場合などでは開発側にのみ存在すべきでしょうか。 |
| $compile_dir | Smartyが生成した解析後のPHPファイル用のディレクトリです。 ここのサイトではこのディレクトリだけ設定しています。 |
| $config_dir | テンプレート用の設定ファイル |
| $cache_dir | Smartyが生成したHTMLファイル用のディレクトリです。 |
define.php
if (!defined('_DEFINE_PHP_')) { define('_DEFINE_PHP_', true); if (!defined('BASE_DIR')) { /* include/define.php 18文字分をトリム */ define('BASE_DIR', substr(__FILE__,0,-18)); } /* インクルードディレクトリ定義 */ define('INCLUDE_DIR',BASE_DIR.'include/'); /* SMARTY関連ディレクトリ定義 */ define('SMARTY_DIR',INCLUDE_DIR.'Smarty/'); define('COMPILE_DIR', BASE_DIR.'templates_c/'); define('CONFIG_DIR', SMARTY_DIR.'configs/'); define('CACHE_DIR', BASE_DIR.'cache/'); define('TEMPLATE_DIR', BASE_PATH.'templates/'); }
smarty.php
require_once "../include/define.php"; require_once SMARTY_DIR."Smarty.class.php"; require_once INCLUDE_DIR."rkt_calendar.php"; /* Smartyオブジェクトの生成 */ $tpl = new Smarty; $tpl->compile_check = true; $tpl->debugging = false; $tpl->caching = 0; $tpl->template_dir = TEMPLATE_DIR; $tpl->compile_dir = COMPILE_DIR; $tpl->config_dir = CONFIG_DIR; $tpl->cache_dir = CACHE_DIR; /* カレンダーオブジェクト */ $objcal = new RKT_calendar($date); $cals = $objcal->getCalendar(); $dates = $objcal->getDates(); $days = array(); foreach ($cals as $weekly=>$days){ foreach ($days as $day){ $cal[$weekly]['week'][$week] = array('day'=>$day); } } // foreach ($cals as $weekly=>$days) /* 変数の受け渡し */ $tpl->assign("cal", $cal); $tpl->assign("month", $dates[RKT_MONTH]); /* テンプレートファイルの読み込みと表示 */ $tpl->display('Smarty.tpl');
Smarty.tpl
<table cellpadding="3" cellspacing="0" align="center" class="calendar"> <tr class="calendar"> <th class="calendar" colspan="7">{$month}月</th> </tr> <tr class="calendar"> <td class="holiday">日</td> <td class="calendar">月</td> <td class="calendar">火</td> <td class="calendar">水</td> <td class="calendar">木</td> <td class="calendar">金</td> <td class="saturday">土</td> </tr> {section name=cal loop=$cal} <tr class="calendar"> {section name=week loop=$cal[cal].week} <td>{$cal[cal].week[week].day}</td> {/section} </tr> {/section} </table>

