可以使用一些自定义代码。
基本上,您希望覆盖控制器的 render() 方法并包含获取当前捆绑包名称的逻辑。
请注意,我的控制器不是扩展Symfony\Bundle\FrameworkBundle\Controller\Controller,而是扩展了一个自定义控制器(然后扩展了 Symfony 的控制器)。这允许您通过添加自己的方法方便地为控制器提供更多功能。
例如:
MyBundle\Controller\MyController\ 扩展 MyCustomBaseController 扩展 Symfony\Bundle\FrameworkBundle\Controller\Controller。
所以,在我的自定义控制器中,我有以下两种方法:
public function render($view, array $parameters = array(), Response $response = null) {
$currentBundle = $this->getCurrentBundle();
$view = str_replace('*', $currentBundle, $view);
return parent::render($view, $parameters, $response);
}
public function getCurrentBundle() {
$controller = $this->getRequest()->attributes->get('_controller');
$splitController = explode('\\', $controller);
return $splitController[1];
}
看看render()。它获取当前包名称并使用它来构建$view 变量。然后它只调用parent::render(),就好像您在渲染语句中手动定义了包名称一样。
这里的代码很简单,所以你应该可以很容易地扩展它来做其他事情,比如让你也可以避免输入控制器名称。
重要提示:如果您使用自定义控制器,请确保您使用use Symfony\Component\HttpFoundation\Response,否则 PHP 会抱怨 render() 的方法签名不匹配。