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.

M
Written by
Mutual
Published 23 Apr 2016
2 min read

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.

Further reading

Craft CMS
Craft CMS 5.10: Safer Deletes, Time Zones, and an Important Security Fix
4 min
Craft CMS
Why use Craft CMS instead of WordPress?
9 min
Analytics
Privacy-First Analytics, Built Into Your CMS
3 min

Let's get your site
where it should be

Emma Andrew

Start a conversation with Emma and Andrew

Emma, Operations Director · Andrew, Technical Director

hello@mutual.agency