Stefano Stefano - 1 month ago 18
PHP Question

Dynamic menu with symfony in template

I'm building a symfony website and I've my own code to build dynamically a menu with subitems. Right now I print it with a bit of twig code inside the base.html.twig file (master layout). The problem is when I need to pass the array with the items of the menu. I'm actually passing it to the render method of a single controller but obvsiously when I switch page I get a non-existent variable. How can I have a single location to put my php code to build the menu array and execute it every time a page is rendered?

Answer

Put your menu-creating logic in a new controller, and use twig's {% render %} to include it in your page. See embedding controllers.