0

假设我有 2 个控制器,内容和新闻:

class ContentController extends Symfony\Bundle\FrameworkBundle\Controller\Controller {
  public function indexAction() {}
}

class NewsController extends ContentController {}

如果新闻控制器的 indexAction 视图不存在(indexAction 继承自父类),我希望 Symfony 使用 Content 控制器的视图(indexAction)。我怎样才能做到这一点?Symfony 总是尝试渲染视图 News/index.html.php,但如果这个视图不存在,我希望 Symfony 渲染 Content/index.html.php。

是否可以告诉 Symfony 渲染引擎这样的事情:如果存在文件 News/index.html.php 取这个,否则取 Content/index.html.php

我使用的是 PHP 模板引擎,而不是 Twig。

我们目前正在使用 Zend 框架,您可以简单地添加一个脚本(视图)路径,如此处所述在 Zend 框架中查看重载

4

1 回答 1

0

我希望我能正确理解你,这可以解决你的问题:

class ContentController extends Symfony\Bundle\FrameworkBundle\Controller\Controller
{
    /**
     * @Route("/", name="content_index")
     */
    public function indexAction()
    {
        // render Content/index.html.php
    }
}

class NewsController extends ContentController
{
    /**
     * @Route("/news", name="content_news_index")
     */
    public function indexAction()
    {
        parent::indexAction();

        // render News/index.html.php
    }
}

您必须根据需要调整路线。


评论中要求的其他方法:

use Symfony\Component\HttpFoundation\Request;

class ContentController extends Symfony\Bundle\FrameworkBundle\Controller\Controller
{
    /**
     * @Route("/", name="content_index")
     * @Route("/news", name="content_news_index")
     */
    public function indexAction(Request $request)
    {
        $routeName = $request->get('_route');

        if ($routeName === 'content_index') {
            // render Content/index.html.php
        } elseif ($routeName === 'content_news_index') {
            // render News/index.html.php
        }        
    }
}
于 2018-11-23T09:56:03.933 回答