Twig macros are how you keep Craft templates DRY. A card component, a button, a media block — anywhere you're repeating markup with small variations, a macro is the right tool.
A basic card macro
Start with something common: a card that previews content and links to a fuller version. Different cards need different things — some clickable, some not; some with images, some without.
The problem with sequential parameters
Define the macro as card(title, body, url, image) and callers have to remember the order. Come back to it a few weeks later and you're counting commas to work out which argument is which. If you want to skip url but pass image, you end up with card('Title', 'Body', null, '/img.jpg') — ugly and easy to get wrong.
Use a single attributes array
Pass one attributes array instead of a long parameter list:
- Readable at the call site — each value is named
- Flexible — callers can pass only what they need
- Self-documenting — the keys describe the data
Add default values
Jeremy Daalder's suggestion: give the macro a default attributes array and merge the caller's values over the top. No more conditionals sprinkled through templates to handle missing keys, and call sites only pass what differs from the default.
Related reading
Similar approaches from Jamie Pittock and Megan Zlock's component-based pattern on GitHub — worth a look if you're pushing macros further.
More from The Journal
Craft CMS 5.11: Login Fixes, a GraphQL Change, and a Round of Security Patches
Craft CMS 5.11 repairs passkey and two-factor logins, tightens up who can query user data over the API, and patches eleven security advisories. Here's what we reckon site owners need to know.
Too Big for Squarespace, Too Small for Adobe: An AI CMS That Fits
Enterprise CMS platforms can be too complex and too expensive for a small marketing team, but the basic builders are too limiting. Our middle ground is an intuitive AI-supercharged CMS you actually own.
"Craft Pulse" plugins temporarily removed from Craft Plugin store
On 14th August we became aware that the plugins from the developer, "Craft Pulse" has been removed. Here's a guide about how you can identify if you're using those plugins.