背景:我想改变一个自编写的Twig扩展.该类定义如下:
class pagination extends \Twig_Extension {
protected $generator;
public function __construct($generator){
$this->generator = $generator;
}
....
}
Run Code Online (Sandbox Code Playgroud)
在其中一种方法中我想生成这样的URL:
$this->generator->generate($route, array('routeParam' => $value);
Run Code Online (Sandbox Code Playgroud)
但问题是,有些路由没有param'routeParam',以这种方式生成路由会导致异常.
我的问题是:如何确定某条路线在该方法中是否具有某些参数?
要检查您的路线是否包含编译路线所需的所有参数,要编译路线,您需要路由器服务,以便通过@service_container添加服务定义将服务传递到您的枝条扩展
somename.twig.pagination_extension:
class: Yournamesapce\YourBundle\Twig\Pagination
arguments: [ '@your_generator_service','@service_container' ]
tags:
- { name: twig.extension } ...
Run Code Online (Sandbox Code Playgroud)
然后在你的类中获取容器然后从容器获取路由器服务并通过getRouteCollection()所有路由获得所需的路径来获取所有路由$routes->get($route)然后编译该路由,一旦你有一个符合的路由定义,你就可以获得路由所需的所有参数通过调用getVariables()哪个将返回参数数组,并在生成检入数组之前(如果routeParam存在)
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);
}
}
....
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
201 次 |
| 最近记录: |