Search code examples
symfonytwig

Pass variable in twig to included template


I have set the rendering of an navigation menu en an separate twig template. Reason is the the menu is generated on two different places in the application.

Now I want to give a parameter to the navigation menu so I know from with place it is generated are these some small differences.

I tried the following code but the variable is not know in the navigation menu template:

{% set menuType = 'user' %}
{% include 'MyBundle:nav.html.twig' with menuType %}

Also tried:

{% include 'MyBundle:nav.html.twig' with {'menuType': 'user'} %}

In both case twig generated the error that {{ menuType }} does not exists?


Solution

  • Surprisingly, while I thought it would be possible to do like you to pass a simple variable, it appears only arrays are accepted as passed values. (While the two examples of the include doc are arrays, this isn't specifically precised.)

    In your case, you have to write it this way:

    {% set menuType = 'user' %}
    {% include 'MyBundle:nav.html.twig' with {menuType:menuType} only %}
    

    Note: I've added the only keyword to disable the access to the context. Without it you don't need to pass the variable to the included templates as they will have access to them. (It's a good practice to disable it.)

    Here is a Twigfiddle with some tests and dumps: https://twigfiddle.com/gtnqvv

    {% set menuType = 'user' %}
    {% set vars = {'foo': 'bar'} %}
    {% set z = 'bob' %}
    
    {# vars dumps ommitted here, see the fiddle. #}
    
    {#% include '1.html.twig' with menuType only %#}
    {% include '1.html.twig' with {menuType:menuType} only %}
    {% include '2.html.twig' with vars only %}
    {% include '3.html.twig' with {z:z} only %}
    {#% include '3.html.twig' with z only %#}
    

    The first and last commented lines doesn't work, as you know, here is the error:

    Uncaught TypeError: Argument 1 passed to Twig_Template::display() must be of the type array, string given

    The second works as you want, you just have to make it an array. (Strange anyway)

    The third line is a test from the Twig doc, and the fourth is a test with another variable name, just to be sure.