SourceForge.jp

Smartyを使う

作成者:開発者   登録日:2007-06-17

  コントローラークラスをオーバーライドしてするサンプルです。action関数内は全く変更せずにSmartyを使用することが出来ます。共通テンプレートを使用できるので作成も楽になります。ちなみに動作サンプルはチュートリアルのブログをSmarty仕様にしたものです。template_cディレクトリの属性を変更するのを忘れないようにして下さい。

  まずCControllerをオーバーライドしたCSmartyControllerを作成します。コンストラクタでSmartyオブジェクトを作成し、set関数をオーバーライドすることでSmarty用の動作に変更します。

smarty_controller.php
require_once 'Smarty.class.php';

class CSmartyController extends CController
{
var $smarty;
var $viewfile_ext = ".tpl";

function CSmartyController()
{
$this->smarty = new Smarty;
$this->smarty->compile_check = true;
}
function set( $key, $value )
{
$this->smarty->assign( $key, $value );
}
}

  次にCViewをオーバーライドしたCSmartyViewを作成します。表示部分をSmarty用の動作に変更します。

smarty_view.php
class CSmartyView extends CView
{
function display()
{
$viewfile = $this->controller->GetViewFile();
$contents = $this->controller->smarty->fetch( $viewfile );
$this->controller->smarty->assign( 'contents', $contents );
$this->controller->smarty->display( $this->template );
}
}

 

  次にconfig.phpにおいて、上記で作成したクラスを適用すれば終了です。

config.php
function config_controller_class()
{
require_once( 'smarty_controller.php' );
return 'CSmartyController';
}
function config_view_class()
{
require_once( 'smarty_view.php' );
return 'CSmartyView';
}
function config_controller( &$controller )
{
$controller->SetTemplateFile( 'template.tpl' );
}

 

ちなみに使い方はこんな感じになります。

test.php
require_once 'config.php';
require_once 'cheetan.php';
function action( &$c )
{
$c->set( 'foo', 'Hello, world!' );
}
test.tpl
<h1>TEST</h1>
{$foo}
template.tpl
<html>
<body>
{$contents}
</body>
</html>

  

デモページ
ダウンロード