Search code examples
phpsymfonytwig

Symfony how to include controller on base.html.twig


I have a small question, I'm new to symfony, I created a controller and a menu template that I want to integrate into my base.html.twig.

I absolutely need the controller to be called because I am testing to know if the session variable is empty or not.

    {% block menu %}
    {% include 'menu/index.html.twig' %}
    {% endblock %}
    
    <body>
        {% block body %}{% endblock %}
    </body>

So I tried this (it works perfectly BUT it didn't call my controller so when I do my test on session it won't work....)

I searched but I can't include the controller instead of the template...

thanks in advance


Solution

  • In Symfony, you cannot call a Controller from inside a twig, what you can do is store variables inside a Controller, and then call those variables from inside the twig.

    For example, in your case, in the Controller you create your variable and save it in the session as follows:

    //...
    class BaseController extends AbstractController
    {
    //...
    
    $session->set('var_i_need', 222);
    
    return $this->render('menu/index.html.twig', [
    'controller_name' => 'BaseController',
    ]);
    
    }
    

    Then inside the twig you get the variable:

    {% set var_i_need = app.session.get('var_i_need') %}
    

    And test if it is empty or not:

    {% if var_i_need is not NULL %}
    {% ... %}
    {% endif %}