我如何在伏特中使用函数或方法?
一个与此相同的功能:
function SumNumber($number1,$numbertwo)
{
return $number1+$numbertwo;
}
或控制器上的此方法
public function SumNumber($number1,$numbertwo)
{
return $number1+$numbertwo;
}
如何通过控制器注册此功能或方法?
答案 0 :(得分:0)
至于Phalcon 1.3.x,首先添加以下PHP代码。不知道是否需要引擎注册,但它对我有用:
$di->set('view', function () use ($config) {
$view = new \Phalcon\Mvc\View();
$view->setViewsDir($config->application->viewsDir);
$view->registerEngines(array(
'.volt' => function ($view, $di) use ($config) {
$volt = new \Phalcon\Mvc\View\Engine\Volt($view, $di);
$options = array(
'compiledPath' => $config->application->cacheDir,
'compiledSeparator' => '_'
);
$volt->setOptions($options);
$compiler = $volt->getCompiler();
$compiler->addFunction('include_raw', function ($resolvedArgs, $exprArgs) use ($view) {
return sprintf('file_get_contents("%s" . %s)', $view->getViewsDir(), $resolvedArgs);
});
[....]
return $volt;
}
));
return $view;
});
在模板中,您可以这样调用函数:
{{ include_raw("partials/somePopup.hbs") }}
答案 1 :(得分:0)
我认为这是一个很好的做法:
一个。创建课程实用程序:
/**
* Put here all utility methods you need in views/controllers
*/
class Utility{
function myCustomMethod($param){
//Do some stuff here...
}
...
}
B中。并在 BaseController.php 的 initialize()方法中添加一个实例:
abstract class ControllerBase extends Controller
{
/**
* Will run when every child controller/action is called,
* if method is not overridden
*/
public function initialize(){
//$this->utility can be used in child controller
$this->utility = new Utility();
/**
* To call from view.
* Volt eg. {{ utility.myCustomMethod('param_data_here') }}
*/
$this->view->utility = $this->utility;
...