Mimicking Slots with Nunjucks Macros

Slots are a fantastic feature provided by modern JS frameworks like React, Vue, and Svelte. At first glance, it appears that this feature is missing in Nunjucks, a very popular templating language used by tools Like Eleventy.

However, after some trial and error, I have discovered a way to mimic it!

While it certainly isn't quite as elegant, here is how it can be accomplished.

<!-- Declaring Macro -->{%macroarticle(slot)%}<article>{{slot| safe}}</article>{%endmacro%}<!-- Declaring Slot Content -->{%setmarkup%}<div><p>I am a block of markup being passed to a macro!</p></div>{%endset%}<!-- Passing Slot to Macro -->{{article(slot=markup)}}<!-- Output: --><article><div><p>I am a block of markup being passed to a macro!</p></div></article>