symfonyvarnishesi

ESI cache on specific route


How could I get varnish to cache a dynamic menu in its different state?

My current project (based on Symfony 2.8) uses the KnpMenuBundle and varnish to cache pages. It also make use of ESI in order to disable cache one specific element on some pages. Among those is the menu. But since this is not an element that changes much, I was wondering if it would be possible to cache the different states of the menu and pass the relevant one to the page currently calling the menu.

The main files involved are the following:

main.html.twig

{{ render_esi(controller('AppBundle:Menu:mainESI')) }}

AppBundle\Controller\MenuController.php

    public function mainESIAction($path = null)
    {
        return $this->render('menu/main_menu_esi.html.twig', [
            'path' => $path
        ]);
    }

menu/main_menu_esi.html.twig

    {{ knp_menu_render('main-menu', {'template':'menu/main_menu.html.twig'}) }}

Solution

  • You can't.

    For Varnish, the url will be the same, so it will render the same.

    Apply your logic outside and add a parameter to your route :

    {% if is_granted('ROLE_ADMIN') %}
        {% set menu_mode = 'admin' %}
    {% else %}
        {% set menu_mode = 'normal' %}
    {% endif %}
    
    {{ render_ssi(controller('AppBundle:Menu:mainESI',{'menu_mode':menu_mode}))  }}