[英]How can I set own Tag class in Volt (Phalcon)
I want to redeclare and add some methods to helper Tag. 我想重新声明并添加一些方法来帮助Tag。
class MyTags extends \Phalcon\Tag
{
public static function mytag($params)
{
<...>
}
}
in services.php 在services.php中
$di->set('tag', function() {
return new MyTags();
};
But it works only for PHP engine, not for Volt. 但它只适用于PHP引擎,而不适用于Volt。
{{ mytag() }}
returned 回来
Undefined function 'mytag'
First of all: don't use tag
as your service name because it's already used by Phalcon's Tag object. 首先:不要使用
tag
作为服务名称,因为它已经被Phalcon的Tag对象使用。 Secondly you can use static methods from class. 其次,您可以使用类中的静态方法。
Below is a working example for myTag
using config from my app with changed names for your example. 下面是
myTag
一个工作示例, myTag
使用我的应用程序中的配置,并为您的示例更改了名称。
$di->set(
'view',
function () use ($config) {
$view = new View();
$view->setViewsDir($config->application->viewsDir);
$view->registerEngines(
array(
'.volt' => function ($view, $di) use ($config) {
$volt = new VoltEngine($view, $di);
$volt->setOptions(
array(
'compiledPath' => $config->application->cacheDir,
'compiledSeparator' => '_',
'compileAlways' => false
)
);
$compiler = $volt->getCompiler();
// add a function
$compiler->addFunction(
'myTag',
function ($resolvedArgs, $exprArgs) {
return 'MyTags::mytag(' . $resolvedArgs . ')';
}
);
// or filter
$compiler->addFilter(
'myFilter',
function ($resolvedArgs, $exprArgs) {
return 'MyTags::mytag(' . $resolvedArgs . ')';
}
);
return $volt;
}
)
);
return $view;
},
true
);
Then you can use your myTag()
function in volt views. 然后你可以在伏特视图中使用
myTag()
函数。
But if you want to use object then don't use static methods: 但是如果你想使用object,那么不要使用静态方法:
class MyTags extends \Phalcon\Tag
{
/**
* Look no static keyword here
*/
public function mytag($params)
{
<...>
}
}
in services use object: 在服务中使用对象:
$di->set('mahTag', function() {
return new MyTags();
};
and then in in volt: 然后在伏特:
{{ mahTag.mytag() }}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.