FuelPHPでSmartyに動的プラグインを仕込む
FuelPHPでSmartyを使い
SmartyのregisterPlugin関数を使う際のメモ
FuelPHPでSmartyを使う場合
FuelPHP1.7.3のテンプレートエンジンにsmartyを設定
こちらのサイトを参考にしてください。
やりたい事は、
テンプレート内で
{less file="style"}
こんな関数を使いたい。
どんな処理をしたいかというと
LESSを自動的にコンパイルし、コンパイルされたcssのパスを表示したい
/app/classes/controller/index.php
class Controller_Index extends \Controller
{
public function action_index(){
$view = \View_Smarty::forge('index');
return $view;
}
}
/app/views/index.tpl
{less file="style"}
まず、この状態では、エラーになる。
lessなんて関数はSmartyにはないから当たり前。
なので、Controller側でSmartyに関数を登録します。
/app/classes/controller/index.php
class Controller_Index extends \Controller
{
public function action_index()
{
\View_Smarty::parser()->registerPlugin('function', 'less', array($this,'smarty_function_less')); //←追記
$view = \View_Smarty::forge('index');
return $view;
}
// ↓追記
public function smarty_function_less($params, $smarty)
{
$file = $params['file'];
if( !preg_match('/\.less$/',$file ) )
{
$file .= '.less';
}
return \Asset::less($file);
}
}
\View_Smarty::parser()->registerPlugin('function', 'less', array($this,'smarty_function_less'));
\View_Smartyからparser()関数でSmartyのクラスを取得します。
staticなクラスが獲得できるので、これに対してregisterPlugin()すれば
恒久的に関数を登録できます。
lessというfunctionを登録し、
実際に処理されるのは、$thisのsmarty_function_lessという関数
$file = $params['file'];
if( !preg_match('/\.less$/',$file ) )
{
$file .= '.less';
}
拡張子が無かったら補完してあげる。
return \Asset::less($file);
LESSをコンパイルしてパスを返す
実行すると、
{less file="style"}
が、
<link type="text/css" rel="stylesheet" href="/assets/ccss/style.css?1523197338" />
こんな感じで変換されます。
LESSを使うための解説は
CentOS7でFuelPHPでlessを使う
を参考にして下さい。
