mozilla / nunjucks

A powerful templating engine with inheritance, asynchronous control, and more (jinja2 inspired)
https://mozilla.github.io/nunjucks/
BSD 2-Clause "Simplified" License
8.48k stars 634 forks source link

how to 'wrap' a macro #1464

Open joelanman opened 2 months ago

joelanman commented 2 months ago

Thanks for Nunjucks! On the GOV.UK Prototype Kit we use it extensively, and one thing we do is load in macros through a custom plugin system.

We do that in a base layout file (lets say that is called base.njk).

I'm trying to wrap some macros from one plugin to add functionality to them (set some default values). So I want to do something like this (slightly simplified):

{% set _myComponent = myComponent %}

{% macro myComponent(option1, option2) %}
  {% set option2 = option2 or "value2" %}
  {{ _myComponent(option1, option2) }}
{% endmacro %}

If I do this in the same file that myComponent is imported in, this works. However due to constraints in the plugin system I can't do it there, so I'm trying to do it in a child layout that extends base.njk. If I do that it stops working, it seems myComponent is available as a macro to run, but can't be reassigned (it says myComponent is undefined). So doing it with a new name works but isn't what I need:

{% macro myNewComponent(option1, option2) %}
  {% set option2 = option2 or "value2" %}
  {{ myComponent(option1, option2) }}
{% endmacro %}

Is there a way to achieve 'wrapping' like this in a child layout, or method other than reassigning it in the same layout?