Skip to content
Mutual Team

Supercharge Macros in Craft CMS

Note: This article was last updated on April 23, 2016 and may contain outdated information.

Macros in Craft CMS and Twig are powerful tools for maintaining clean, DRY code. They help developers eliminate redundancy, simplify maintenance, and accelerate development workflows.

Building a Basic Card Interface

The article demonstrates constructing a simple card macro as a foundational example. Cards are common UI components that preview content and often link to fuller versions. Different card implementations may require varying features—some clickable, others static; some with images, others without.

The Problem with Sequential Parameters

When adding complexity like URLs and images, defining parameters in strict order creates confusion and readability issues. Returning to such code weeks later becomes problematic: “sometimes we don’t want them clickable, and sometimes we might not [want] images. But because the parameters need to be defined in order we have to start doing this…”

The Solution: Attribute Arrays

Rather than stacking parameters, the author recommends using a single “attributes” parameter structured as an array. This approach offers three key advantages:

— Improved readability — Greater flexibility — Self-documenting code

Enhanced Approach: Default Values

Jeremy Daalder suggested incorporating default attributes that can be overridden per instance. This pattern eliminates scattered conditional statements throughout templates while keeping individual attribute arrays minimal and maintainable.

The article references similar methodologies by Jamie Pittock and Megan Zlock’s component-based approach on GitHub, validating this architectural pattern across the Craft CMS community.