I created a custom theme called wdocs as a sub theme of d8w3css. I made a template to override the menu template for the user account menu, calling it menu--account.html.twig. For my theme, I added the function wdocs_preprocess_menu__account() to my wdocs.theme file, and introduced a new variable with $variables['tollfree_number'] = '555-1212'; So far so good; in phpStorm I can set a breakpoint there are do see it is getting set in $variables. In my twig, I have some text, followed by {{ tollfree_number }}. The text gets displayed, but not the variable.

The problem is the twig calls a macro; I can access the var outside of the macro, but not within it. Googling suggested I pass context when calling the macro, so I changed the call to

{{ menus.menu_links(items, attributes, 0, menu_name, _context) }}

I also tried "context" (no underscore). And also tried dereferencing it with {{ _context['tollfree_number'] }}, but nothing seems to help. Where am I going wrong?

  • 1
    You would need to change the macro definition as well. Or simply put the variable in an item below $variables['items'] and then display it: {{ item.foo }} – 4k4 Aug 20 '20 at 7:10

You're correct in thinking that trying to access your var from within the macro is the issue. See Twig's macro documentation.

But as with PHP functions, macros don’t have access to the current template variables.

You can pass your variable into the macro.

{{ menus.menu_links(items, attributes, 0, menu_name, tollfree_number) }}

Then you have two options, you can update the macro definition to add an extra parameter for your custom var.

{% macro menu_links(items, attributes, 0, menu_name, toll_free) %}
  {# etc.. #}
  {{ toll_free }}
{% endmacro %}

Or you can use the special varargs variable without updating the macro definition.

If extra positional arguments are passed to a macro, they end up in the special varargs variable as a list of values.

Pass the var to the macro the same way, then access it like:

{% macro menu_links(items, attributes, 0, menu_name) %}
  {# varargs[0] has the first extra arg, varargs[1] has the second, etc #}
  {{ varargs[0] }}
{% endmacro %}

Using the special _context and varargs vars:

{{ menus.menu_links(items, attributes, 0, menu_name, _context) }}

{% macro menu_links(items, attributes, 0, menu_name) %}
  {{ varargs[0].tollfree_number }}
{% endmacro %}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.