返回首页 - Notes - 2015

在 Symfony2 框架的 Twig 模版中获取当前路由的一些信息


可以直接取到的数据


获取单纯的控制器名和方法名

  1. XXX/YYYBundle 目录下创建目录结构:Twig/Extension
  2. XXX/YYYBundle/Twig/Extension 目录下创建文件 ControllerActionExtension.php
  3. 往该文件写入以下内容:
    <?php namespace XXX\YYYBundle\Twig\Extension;
    
    use Symfony\Component\HttpFoundation\Request;
    
    class ControllerActionExtension extends \Twig_Extension {
    
        protected $request;
        protected $environment;
    
        public function setRequest (Request $request = null) {
            $this->request = $request;
        }
    
    
        public function initRuntime (\Twig_Environment $environment) {
            $this->environment = $environment;
        }
    
    
        public function getFunctions () {
            return [
                'controller_name' => new \Twig_Function_Method($this, 'getControllerName'),
                'action_name'     => new \Twig_Function_Method($this, 'getActionName'),
            ];
        }
    
    
        public function getControllerName () {
            if ($this->request !== null) {
                preg_match("#Controller\\\([a-zA-Z]*)Controller#", $this->request->get('_controller'), $match);
    
                return strtolower(@$match[1]);
            }
        }
    
    
        public function getActionName () {
            if ($this->request !== null) {
                preg_match("#::([a-zA-Z]*)Action#", $this->request->get('_controller'), $match);
    
                return $match[1];
            }
        }
    
    
        public function getName () {
            return 'get_current_controller_action_twig_extension';
        }
    
    }
    
  4. 编辑文件 Ruchee/BlogBundle/Resources/config/services.yml,写入以下内容:
    services:
        xxx.yyybundle.twig.controller_action_extension:
            class: XXX\YYYBundle\Twig\Extension\ControllerActionExtension
            calls:
                - [setRequest, ["@?request="]]
            tags:
                - { name: twig.extension }
    
  5. 然后就可以在 Twig 模版里面这样使用了:{{ controller_name() }}{{ action_name() }}

date:2015-04-24