DEV Community

loading...

Mimicking Slots with Nunjucks Macros

mattwaler profile image Matt Waler ・1 min read

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 -->
{% macro article(slot) %}
  <article>
    {{ slot | safe }}
  </article>
{% endmacro %}

<!-- Declaring Slot Content -->
{% set markup %}
  <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>
Enter fullscreen mode Exit fullscreen mode

I hope I could help you dry up some markup!

Discussion (0)

pic
Editor guide