Add data to return of all actions in a Symfony controller

后端 未结 2 1596
一向
一向 2021-01-24 09:24

I have a controller in a Symfony 2.1 application, let\'s just call it FooController in the BarBundle. This controller has a lot of actions fooAct

相关标签:
2条回答
  • 2021-01-24 09:41

    One option is to create your own base controller, and have all other controller extend it. Your base controller would override the render function of the Controller class from symfony framework

    use Symfony\Bundle\FrameworkBundle\Controller\Controller;
    class BaseController extends Controller
    {
        // override render method
        protected function render($template, $data)
        {
            $commonData = [];// get data from wherever you need
            parent::render($template, $data + $commonData);
        }
    }
    

    Then in your other controllers

    class MyAnotherController extends BaseController
    {
        public function fooAction() {
        // ...
        return $this->render('BarBundle:Foo:foo.html.twig', array('foo' => 'Foo Data'));
        }
    }
    
    0 讨论(0)
  • 2021-01-24 09:42

    One of options

    public function commonAction($type) {
         // ...
         return $this->render('BarBundle:Foo:'.$type.'.html.twig', array('data' => $this->getTheDataThatIsNeededInEveryAction()));
    }
    

    where $type would be bar, foo or baz

    0 讨论(0)
提交回复
热议问题