Skip to content
loading...

Mimicking Slots with Nunjucks Macros

mattwaler profile image Matt Waler github logo ・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>

I hope I could help you dry up some markup!

twitter logo DISCUSS
Discussion
markdown guide
Classic DEV Post from Aug 13 '19

How open-source will Tumblr become?

In case you hadn't read the news, Verizon sold Tumblr to Automattic. Verizon owned Tumblr after it ac...

Matt Waler profile image
Overly generous lover of pragmatic front-end development. In my off-time, you'll find me lifting, gaming, eating, and developing some more.