在TWIG模板中获取控制器名称

Har*_*dya 7 controller symfony twig

我正在学习symfony2.3,当我尝试在twig模板中获取控制器名称时出现错误.

控制器:

namespace Acme\AdminBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;

class DefaultController extends Controller
{
    public function indexAction($name)
    {
        return $this->render('AcmeAdminBundle:Default:index.html.twig', array('name' => $name));
    }
}
Run Code Online (Sandbox Code Playgroud)

在我的TWIG模板中:

{% extends '::base.html.twig' %}
{% block body %}
 {{ app.request.get('_template').get('controller') }}
 Hello {{ name }}!!!
{% endblock %}
Run Code Online (Sandbox Code Playgroud)

输出:

Impossible to invoke a method ("get") on a NULL variable ("") in AcmeAdminBundle:Default:index.html.twig at line 3 
Run Code Online (Sandbox Code Playgroud)

我希望输出为"默认"

我正在使用symfony 2.3,我也试过symfony 2.1,但两个版本都生成相同的错误.

Sha*_*man 25

使用此行在树枝中显示控制器名称:

{{ app.request.attributes.get("_controller") }}
Run Code Online (Sandbox Code Playgroud)

  • 天啊!!`{{ app.request.attributes.get("_route") }}` 用于路由名称。 (4认同)
  • 我不知道为什么这不是公认的,投票最多的答案,内置简单易用的东西,怎么了? (2认同)

Dan*_*cas 17

几个月前,我遇到了和你一样的问题,并且"谷歌搜索"我发现了一个正常工作的代码,我已经将它改编成了我的必需品.开始了:

1 -我们需要为此定义一个TWIG扩展.如果您尚未定义,我们将创建文件夹结构Your\OwnBundle\Twig\Extension.

2 -在这个文件夹里面我们创建了一个文件ControllerActionExtension.php,代码是:

namespace Your\OwnBundle\Twig\Extension;

use Symfony\Component\HttpFoundation\Request;

/**
 * A TWIG Extension which allows to show Controller and Action name in a TWIG view.
 * 
 * The Controller/Action name will be shown in lowercase. For example: 'default' or 'index'
 * 
 */
class ControllerActionExtension extends \Twig_Extension
{
    /**
     * @var Request 
     */
    protected $request;

   /**
    * @var \Twig_Environment
    */
    protected $environment;

    public function setRequest(Request $request = null)
    {
        $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()
    {
        if(null !== $this->request)
        {
            $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()
    {
        if(null !== $this->request)
        {
            $pattern = "#::([a-zA-Z]*)Action#";
            $matches = array();
            preg_match($pattern, $this->request->get('_controller'), $matches);

            return $matches[1];
        }
    }

    public function getName()
    {
        return 'your_own_controller_action_twig_extension';
    }
}
Run Code Online (Sandbox Code Playgroud)

3 -之后我们需要指定要识别的TWIG服务:

services:
    your.own.twig.controller_action_extension:
        class: Your\OwnBundle\Twig\Extension\ControllerActionExtension
        calls:
            - [setRequest, ["@?request="]]
        tags:
            - { name: twig.extension }
Run Code Online (Sandbox Code Playgroud)

4 -缓存清除以确保一切正常:

php app/console cache:clear --no-warmup
Run Code Online (Sandbox Code Playgroud)

5 -而现在,如果我不忘记什么,你将能够访问在一根树枝模板的2种方法:get_controller_name()get_action_name()

6 -示例:

You are in the {{ get_action_name() }} action of the {{ get_controller_name() }} controller.
Run Code Online (Sandbox Code Playgroud)

这将输出如下内容:您处于默认控制器的索引操作中.

您还可以使用以检查:

{% if get_controller_name() == 'default' %}
Whatever
{% else %}
Blablabla
{% endif %}
Run Code Online (Sandbox Code Playgroud)

就这样!!我希望我能帮助你,交配:)

编辑:注意清除缓存.如果您不使用--no-warmup参数,您可能会发现模板中没有显示任何内容.那是因为这个TWIG扩展使用Request来提取Controller和Action名称.如果您"预热"缓存,请求与浏览器请求不同,并且方法可以返回''null


小智 5

从Symfony 3.x开始,服务请求被request_stack替换,并且自Twig 1.12以来Twig扩展声明已更改.

我将更正Dani的答案(/sf/answers/1228081641/):

1 -我们需要为此定义一个TWIG扩展.如果你还没有定义,我们创建文件夹结构AppBundle\Twig\Extension.

2 -在这个文件夹里面我们创建了一个文件ControllerActionExtension.php,代码是:

<?php

namespace AppBundle\Twig\Extension;

use Symfony\Component\HttpFoundation\RequestStack;

class ControllerActionExtension extends \Twig_Extension
{
    /** @var RequestStack */
    protected $requestStack;

    public function __construct(RequestStack $requestStack)
    {
        $this->requestStack = $requestStack;
    }

    public function getFunctions()
    {
        return [
            new \Twig_SimpleFunction('getControllerName', [$this, 'getControllerName']),
            new \Twig_SimpleFunction('getActionName', [$this, 'getActionName'])
        ];
    }

    /**
     * Get current controller name
     *
     * @return string
    */
    public function getControllerName()
    {
        $request = $this->requestStack->getCurrentRequest();

        if (null !== $request) {
            $pattern = "#Controller\\\([a-zA-Z]*)Controller#";
            $matches = [];
            preg_match($pattern, $request->get('_controller'), $matches);

            return strtolower($matches[1]);
        }
    }

    /**
     * Get current action name
     *
     * @return string
    */
    public function getActionName()
    {
        $request = $this->requestStack->getCurrentRequest();

        if (null !== $request) {
            $pattern = "#::([a-zA-Z]*)Action#";
            $matches = [];
            preg_match($pattern, $request->get('_controller'), $matches);

            return $matches[1];
        }
    }

    public function getName()
    {
        return 'controller_action_twig_extension';
    }
}
Run Code Online (Sandbox Code Playgroud)

3 -之后我们需要指定要识别的TWIG服务:

app.twig.controller_action_extension:
    class: AppBundle\Twig\Extension\ControllerActionExtension
    arguments: [ '@request_stack' ]
    tags:
        - { name: twig.extension }
Run Code Online (Sandbox Code Playgroud)

4 -缓存清除以确保一切正常:

php bin/console cache:clear --no-warmup
Run Code Online (Sandbox Code Playgroud)

5 -现在,如果我没有忘记任何事情,你将能够在TWIG模板中访问这两个方法:getControllerName()getActionName()

6 -示例:

您处于{{getControllerName()}}控制器的{{getActionName()}}操作中.

这将输出如下内容:您处于默认控制器的索引操作中.

您还可以使用以检查:

{% if getControllerName() == 'default' %}
Whatever
{% else %}
Blablabla
{% endif %}
Run Code Online (Sandbox Code Playgroud)


Tou*_*uki 1

我真的不明白为什么你需要这个。
您最好将参数发送到您的视图中。

但如果你确实需要这种方式,这里有一个解决方案:

你的错误来自第二种get方法

request = app.request              // Request object
NULL    = request.get('_template') // Undefined attribute, default NULL
NULL.get('controller')             // Triggers error
Run Code Online (Sandbox Code Playgroud)

如果您想在请求期间调用控制器,您可以通过_controller请求属性的键访问它

app.request.attribute.get('_controller')
Run Code Online (Sandbox Code Playgroud)

将返回

Acme\AdminBundle\Controller\DefaultController::indexAction
Run Code Online (Sandbox Code Playgroud)

然后您可以按照您想要的方式解析它。

请注意,这不会返回控制器实例,仅返回其名称和调用的方法