Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create ViewHelper in Symfony 2

Tags:

symfony-2.1

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

like image 942
emeraldhieu Avatar asked Oct 05 '22 08:10

emeraldhieu


1 Answers

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();
like image 200
Stephan Schulze Avatar answered Oct 10 '22 04:10

Stephan Schulze