In one of my templates i needed a simple way to get controller / action name to generate some dynamic urls. Symfony2 does not offer any Twig helper function to display current controller / action name.
The easiest way that i have found so far is to create Twig extension. In our default bundle we need to create folder Twig/Extension for example Acme/PageBundle/Twig/Extension and place there our Twig extension class:
<?php
// src/Acme/PageBundle/Twig/Extension/AcmePageExtension.php
namespace Acme\PageBundle\Twig\Extension;
use Symfony\Component\HttpFoundation\Request;
class AcmePageExtension extends \Twig_Extension
{
protected $request;
/**
*
* @var \Twig_Environment
*/
protected $environment;
public function __construct(Request $request)
{
$this->request = $request;
}
public function initRuntime(\Twig_Environment $environment)
{
$this->environment = $environment;
}
public function getFunctions()
{
return array(
'get_controller_name' => new \Twig_Function_Method($this, 'getControllerName'),
'get_action_name' => new \Twig_Function_Method($this, 'getActionName'),
);
}
/**
* Get current controller name
*/
public function getControllerName()
{
$pattern = "#Controller\\\([a-zA-Z]*)Controller#";
$matches = array();
preg_match($pattern, $this->request->get('_controller'), $matches);
return strtolower($matches[1]);
}
/**
* Get current action name
*/
public function getActionName()
{
$pattern = "#::([a-zA-Z]*)Action#";
$matches = array();
preg_match($pattern, $this->request->get('_controller'), $matches);
return $matches[1];
}
public function getName()
{
return 'acme_page';
}
}
Next step is to register this service:
// src/Acme/PageBundle/Resources/config/services.yml
request:
class: Symfony\Component\HttpFoundation\Reques
acme.twig.extension:
class: Acme\PageBundle\Twig\Extension\AcmePageExtension
arguments: [@request]
tags:
- { name: 'twig.extension' }
and then in twig templates we can simply call:
Controller name: {{ get_controller_name() }}
Action name: {{ get_action_name() }}