Symfony 3 view overloading for controller inheritance

537 Views Asked by At

Let's say I have 2 controllers, content and news:

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

and

class NewsController extends ContentController {}

If the view for the indexAction does not exist for the news controller (the indexAction is inherited from the parent class), I want Symfony to use the view of the Content controller (indexAction). How can I achieve this? Symfony always tries to render the view News/index.html.php but if this view does not exist I would like that Symfony renders Content/index.html.php.

Is it possible to tell the Symfony render engine something like this: If there exists the file News/index.html.php take this one, otherwise take Content/index.html.php

I'm using the PHP template engine, not twig.

We are currently using the Zend Framework and there you can simply add a script (view) path as described here View overloading in Zend Framework

1

There are 1 best solutions below

3
On

I hope I understand you correctly and this could fix you problem:

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
    }
}

You have to adjust the routes to your needs.


Additional approach as requested in the comments:

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
        }        
    }
}