1

Printing {{ directory }} at the start of the file works fine. But a bit further it's no longer availble:

{% import _self as menus %}

{#
  We call a macro which calls itself to render the full tree.
  @see http://twig.sensiolabs.org/doc/tags/macro.html
#}
{{ menus.menu_links(items, attributes, 0) }}

{% macro menu_links(items, attributes, menu_level) %}
    **{{ directory }} {# THIS WORKS #}**
    {% import _self as menus %}
    {% if items %}
        {% if menu_level == 0 %}
            <ul{{ attributes }}>
        {% else %}
            <ul id="navigation">
        {% endif %}
        {% for item in items %}
        <li class="active">
            <a href="{{ item.url }}">
                **{{ directory }} {# THIS DOESN'T WORK #}**
                <img src="{{ directory }}/images/menuicon.png" alt="" />
                {{ item.title }}
            </a>
        </li>
        {% endfor %}
        </ul>
    {% endif %}
{% endmacro %}

Any idea why this happens and how to fix it?

1

The second occurrence of {{ directory }} is within a Twig macro. As the Twig documentation mentions, you cannot access the outer variables in a macro:

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

You can however pass _context through a macro parameter and access directory that way, or pass it explicitly.

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.