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

1 Answer 1

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
]);
Sign up to request clarification or add additional context in comments.

1 Comment

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.