Nunjucks macros are like React components
Iain Bean likes to think of Nunjuck macros as React function components. And I agree with him!
Once you have partial files with isolated variable scope and default argument values, you can keep your templates tidy and organized.
If your primary strategy to create dynamic partial files was to use set
and include
, then definitely check his article, as he compares the two approaches.
As additional information, it's good to know that you can use macros as values for the parameters. Similar to how you can pass components to the props.
This should be familiar if you used React:
const TitleWithLink = ({ title, url }) => {
return <a href={url}>{title}</a>;
};
const PostCard = ({ title }) => {
return <h1>{title}</h1>;
};
<PostCard
title={
<TitleWithLink
title="Sponge, to soak up..."
url="http://www.implenton.com/..."
/>
}
/>
<PostCard title="Sponge, to soak up..." />
How does this look in Nunjucks? Like this:
{% raw %}{% from 'post-macros.njk' import card, titleWithLink %}
{{ postCard(titleWithLink(post.data.title, post.url), post.templateContent) }}{% endraw %}
I'm using this exact approach here on implenton.com. And when I don't want the title to contain a link, I simply pass a variable referencing a string:
{% raw %}{{ postCard(post.data.title, post.templateContent) }}{% endraw %}
It's a good way to avoid conditionals, make the partial files more readable, and, in the end, easier to understand.
Also, notice that I'm importing multiple macros from the same file. You can define as many you want in one file and import only what you need. This way, you can keep a few lines macros together.