以以下控制器/操作为例:
public function indexAction()
{
return $this->render('TestBundle:TestController:index.html.twig');
}
我想以这种方式编写模板表达式(或任何名称(:
public function indexAction()
{
return $this->render('*:TestController:index.html.twig');
}
所以symfony知道我正在这个捆绑包中寻找一个模板。必须为我想引用的每个模板/操作/存储库编写整个所有者 + 捆绑包非常烦人。考虑到大多数时候我引用同一捆绑包中的操作和模板,更是如此。
注意:我知道模板可以放在应用程序级别并像这样引用:
'::index.html.twig'
但这不是我所需要的。
这可以通过一些自定义代码来实现。
基本上,您希望覆盖控制器的 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()
就像你在 render 语句中手动定义了捆绑包名称一样。
这里的代码非常简单,因此您应该能够轻松扩展它以执行其他操作,例如允许您也避免键入控制器名称。
重要提示:如果您确实使用自定义控制器,请确保use Symfony'Component'HttpFoundation'Response
,否则 PHP 将抱怨 render()
的方法签名不匹配。