gpt4 book ai didi

php - Symfony2 Controller 和模板表达式可以相对于 bundle 来写吗?

转载 作者:可可西里 更新时间:2023-10-31 23:49:57 27 4
gpt4 key购买 nike

以下面的 Controller / Action 为例:

public function indexAction()
{
return $this->render('TestBundle:TestController:index.html.twig');
}

我想这样写模板表达式(或任何它的名字):

public function indexAction()
{
return $this->render('*:TestController:index.html.twig');
}

这样 symfony 就知道我正在这个包中寻找模板。必须为我想引用的每个模板/操作/存储库编写整个 Owner + Bundle 非常烦人。更重要的是,考虑到我大部分时间都在同一个包中引用操作和模板。

注意:我知道模板可以放在应用程序级别并像这样引用:

'::index.html.twig'

但这不是我需要的。

最佳答案

使用一些自定义代码是可能的。

基本上,您想要覆盖 Controller 的 render() 方法并包含获取当前包名称的逻辑。

请注意,我的 Controller 不是扩展 Symfony\Bundle\FrameworkBundle\Controller\Controller,而是扩展自定义 Controller (然后扩展 Symfony 的 Controller )。这使您可以通过添加自己的方法方便地为 Controller 提供更多功能。

例如:MyBundle\Controller\MyController\ 扩展了 MyCustomBaseController,后者扩展了 Symfony\Bundle\FrameworkBundle\Controller\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() 就好像您在渲染语句中手动定义了包名称一样。

这里的代码非常简单,因此您应该能够轻松地扩展它来做其他事情,例如让您也可以避免键入 Controller 名称。

重要:如果您确实使用自定义 Controller ,请确保您使用 Symfony\Component\HttpFoundation\Response,否则 PHP 会提示 的方法签名>render() 不匹配。

关于php - Symfony2 Controller 和模板表达式可以相对于 bundle 来写吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8395541/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com