2

re: macros I'm trying to use one for an SVG sprite. But I'm not sure what I'm doing wrong.

macros template:

{% macro icon(iconId) %}
    <svg class="icon icon-{{ iconId }}" role="img" title="{{ iconId }}">
        <use xlink:href="{{ url('/assets/images/icons.svg#' ~ iconId) }}"></use>
    </svg>
{% endmacro %}

In my layout template I have this {% import '_macros' as macros %} and in an another template this {{ macros.icon("SIGNAL") }}

Then in the site i get a twig runtime error:

Accessing Twig_Template attributes is forbidden.

and it highlights the line where I extend the layout template.

Not sure why this isn't working.

Without a macro this code works fine. but I want the macro so I don't have to type it out all the time.

<svg class="icon" height="0" width="0">
 <use xlink:href="/assets/images/icons.svg#SIGNAL" />
</svg>
3

This is a change in how macros work in Twig 2.0, not a Craft CMS issue (though Craft 3 did signal a move to Twig 2.x).

As of Twig 2.0, macros imported in a file are not available in child templates anymore (via an include call for instance). You need to import macros explicitly in each file where you are using them.

https://twig.symfony.com/doc/1.x/deprecated.html

This is also documented in the Craft CMS 3 docs:

https://docs.craftcms.com/v3/changes-in-craft-3.html#twig-2

...so just import the macro again in the child template.

  • Thank you Andrew - this is first time using macros. All good now. – CreateSean Jun 28 '18 at 16:37

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.