幾個月前,我有同樣的問題和「谷歌搜索」我找到了一個工作代碼,我已經適應了我的必需品。我們去:
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';
}
}
3 -之後,我們需要指定服務嫩枝被認可:
services:
your.own.twig.controller_action_extension:
class: Your\OwnBundle\Twig\Extension\ControllerActionExtension
calls:
- [setRequest, ["@?request="]]
tags:
- { name: twig.extension }
4 -緩存清理,以確保一切正常:
php app/console cache:clear --no-warmup
5 -現在,如果我不忘記什麼,你將能夠訪問在一根樹枝模板的2種方法:get_controller_name()
和get_action_name()
6 -例子:
You are in the {{ get_action_name() }} action of the {{ get_controller_name() }} controller.
這將輸出的東西例如:您處於默認控制器的索引操作中。
你也可以用它來檢查:
{% if get_controller_name() == 'default' %}
Whatever
{% else %}
Blablabla
{% endif %}
而這一切!我希望我幫你,隊友:)
編輯:注意清除緩存。如果您不使用--no-warmup
參數,您可能會意識到模板中沒有顯示任何內容。這是因爲此TWIG擴展使用請求來提取控制器和操作名稱。如果你「熱身」的高速緩存,該請求是不一樣的瀏覽器請求,並且方法可以返回''
或null
但是,你爲什麼需要這些信息? – j0k
我想添加類到一些鏈接的基礎上的控制器名稱。 –