Encapsulated Eleventy/Nunjucks components with macros (by Trys Mudford)

Direct Link

Trys shows us how to use the Nunjucks macro to create encapsulated components. This works out less leaky and more predictable than an include preceded by variables assigned with set.

Trys’s solution allows us to render components like so:

{{ component('button', {
text: 'Press me'
}) }}

{# Output #}
<button type="button">Press me</button>

Update, 8th Aug 2021: when I tried implementing this I found that it results in errors when attempting to render components anywhere other than on the base template where Trys recommended including the import line. The workaround—as Paul Salaets points out—is to include the import at the top of every page-level template (index.njk, archive.njk etc) that uses the component macro.

External Link Bookmark Note Entry Search