如何在Symfony中创建ViewHelper 2.我阅读了整个文档,但它没有描述任何类似的术语。它只是自动加载和服务。 http://symfony.com/doc/current/cookbook/index.html
答案 0 :(得分:3)
您只需要创建一个实现辅助函数的类并扩展
Symfony\Component\Templating\Helper\Helper
像这样:
namespace Acme\Foo\Helper;
use Symfony\Component\Templating\Helper\Helper;
class MyViewHelper extends Helper {
public function helpMe() {
// do something
return $value;
}
/**
* @inheritdoc
*/
public function getName() {
return "anyCanonicalServiceName";
}
}
然后,您必须将您的助手宣传为具有特殊标签的服务,例如:
Resources/config/services.yml
services:
your_service_name:
class: Acme\Foo\Helper\MyViewHelper
# the tag alias "myViewHelper" is later used in the view to access your service
tags:
- { name: templating.helper, alias: myViewHelper }
现在您可以在以下视图中访问帮助程序:
echo $view['myViewHelper']->helpMe();