Symfony中的树枝模板的通用代码(4)

I'm not understanding how can I make general or common code for my application, for example I have to render all categories to make a HTML menu, and that code is for ALL the website, I can't put that code in only one controller.

Thanks!

You can achieve what you want like this:

/templates/layout/menu.html.twig:

<ul>
    {% for key,value in items %}
        <li>
            <a href="{{ value.link }}">
                {{ key }}
            </a>
        </li>
    {% endfor %}
</ul>

MenuController:

<?php
    namespace App\Controller;

    use Symfony\Bundle\FrameworkBundle\Controller\Controller;

    class MenuController extends Controller
    {
        public function menu()
        {
            $items = array(
                'page' => array('link' => '/page/'),
                'page two' => array('link' => '/page/two')
            );

            return $this->render(
                'layout/menu.html.twig',
                array('items' => $items)
            );
        }
    }

then in your base.html.twig (anywhere)

<div class="menu">
    {{ render(controller(
        'App\\Controller\\MenuController::menu'
    )) }}
</div>

You're looking for this https://symfony.com/doc/4.0/templating.html#template-inheritance-and-layouts

You should have something like this in all your twig files

{% extends 'base.html.twig' %}

And in that base.html.twig you can create your menu just once :)