Supercharge Macros in Craft CMS
Learn how to use macros in Craft CMS and Twig to maintain clean, DRY code with attribute arrays and default values.
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.