0

Recently while building my CMS in Symfony, I've run into a problem. I have 2 controllers, publicationcontroller and contactcontroller. In both controllers, an instance of the entity Page is loaded whenever a corresponding slug matches. Below is the code:

class ContactController extends AbstractController
{
    /**
     * @Route("/{slug}", name="contact")
     */
    public function index(PageRetriever $pageRetriever, $slug)
    {
        $page = $pageRetriever->getPage($slug);

        return $this->render('contact/index.html.twig', [
            'page' => $page
        ]);
    }
}

class PublicationController extends AbstractController
{
    /**
     * @Route("/{slug}", name="publications")
     */
    public function index(PageRetriever $pageRetriever, $slug)
    {
        $page = $pageRetriever->getPage($slug);

        return $this->render('publication/index.html.twig', [
            'page' => $page
        ]);
    }
}

My problem is that both the content of publication and contact are loaded in the same template, depending on which controller is initialized first.

Does anyone here have an idea or some tips on how to load the proper template, depending on which slug is called?

Any hope is greatly appreciated

Dhia Djobbi
  • 1,176
  • 2
  • 15
  • 35
Coderz99
  • 1
  • 3

1 Answers1

1

There is no way Symfony could know which controller should be called. You have same route for both contact and publication controller.

There is 2 possible solutions which I can think of.

1. Use different routes

@Route("/publication/{slug}", name="publications")
@Route("/contact/{slug}", name="contact")

2. Use one controller but write your own logic to choose template

$page = $pageRetriever->getPage($slug);

if ($page->getType() === 'publication') {
    return $this->render('publication/index.html.twig', [
        'page' => $page
    ]);
}

return $this->render('contact/index.html.twig', [
    'page' => $page
]);
Pavol Velky
  • 770
  • 3
  • 9
  • I think option 2 is a good first step. I will try to render the templates from a service like this and try to give them their own controllers – Coderz99 Aug 11 '21 at 05:38