Reputation: 9439
How to create a ViewHelper in Symfony 2. I read whole the documentation but it doesn't describe any term like that. It just has autoloading and service. http://symfony.com/doc/current/cookbook/index.html
Upvotes: 5
Views: 2506
Reputation: 139
You just have to create a class that implements your helper function and extends
Symfony\Component\Templating\Helper\Helper
like this:
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";
}
}
Then you have to promote your helper as a service with a special tag in e.g.
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 }
Now you can access the helper in a view like this:
echo $view['myViewHelper']->helpMe();
Upvotes: 4