Skip to content

đź‘‹ Just to let you know... as a remote team, we're fully operational during the COVID-19 outbreak.


Supercharge Macros in Craft CMS

by Andrew


Macros in Craft CMS (and Twig in general) are insanely useful. You can use them to keep your code nice and DRY (Don't Repeat Yourself) - reducing redundancy, making maintenance easier, and making development faster.

In this example, I'll walk you through how to build a simple 'card' interface. In UI terms, Cards are often little widgets that preview content and when clicked upon open the full thing. Many sites have different kinds of cards - some might be clickable, some might just be static; some might have images, some may not.

Here's how we would construct a basic macro.

The disadvantage of this becomes clear once we start to add complexity. Let's say we wanted to add a few more parameters: the URL to link to and image.

But the problem here is that sometimes we don't want them clickable, and sometimes we might not images. But because the parameters need to be defined in order we have to start doing this…

Which, when we come back to it in 2 weeks time, is going to be completely mind boggling.

So instead I've started to define a single parameter, which I call "attributes" and make that an array. So the example above becomes…

This becomes easy to read, incredibly flexible, and almost self-documenting.

This method can also apply really well with includes, if they're more appropriate for your use case by using Twig's 'with' feature of includes.

Update: Jeremy Daalder suggested a way to build on this a little bit more, with a method that I really like and will be using in future. It involves having defaults for macros, which are then overridden if needs be on a per-instance basis.

For example in this example we may want to have a default colour scheme of "light" and a size of "standard", but throughout the site we might need to mix that up. Having a defaults array means that we avoid if statements all over the place ("if this isn't set, set it as light"), and can keep the majority of the attribute arrays around the site minimal.

This example is basic, it's only setting additional CSS classes. But you could use it to affect the macro in more dramatic ways.

Jamie Pittock uses a similar method which he describes in detail on Stack Exchange, and Megan Zlock has made a GitHub repository with a demo website using components in a similar way.