Reputation: 1104
Background: I want to alter a self written Twig extension. The class is defined as follows:
class pagination extends \Twig_Extension {
protected $generator;
public function __construct($generator){
$this->generator = $generator;
}
....
}
In one of the methods i want to generate an URL like this:
$this->generator->generate($route, array('routeParam' => $value);
But the problem is, that some routes don't have the param 'routeParam' whichg would cause an Exception when generating the route this way.
My question is: How can i find out if a given route has certain paramters in that method?
Upvotes: 6
Views: 529
Reputation: 64476
To check your route has all the params you need to compile your route , to compile route you need router service so pass @service_container
service to your twig extension by adding in your service definition
somename.twig.pagination_extension:
class: Yournamesapce\YourBundle\Twig\Pagination
arguments: [ '@your_generator_service','@service_container' ]
tags:
- { name: twig.extension } ...
And in your class get container then get router service from container and get all routes by getRouteCollection()
once you have all routes get the desired route fro collection by $routes->get($route)
then compile that route,once your have a complied route definition you can get all the params required for route by calling getVariables()
which will return array of parameters and before generating check in array if routeParam
exists
use Symfony\Component\DependencyInjection\ContainerInterface as Container;
class Pagination extends \Twig_Extension {
protected $generator;
private $container;
public function __construct($generator,Container $container){
$this->generator = $generator;
$this->container = $container;
}
public function somefunction(){
$routes = $this->container->get('router')->getRouteCollection();
$routeDefinition = $routes->get($route);
$compiledRoute = $routeDefinition->compile();
$all_params = $compiledRoute->getVariables();
if(in_array('routeParam',$all_params)){
$this->generator->generate($route, array('routeParam' => $value);
}
}
....
}
Upvotes: 6