How to use Macros with Twig in Craft CMS — DRY

Templating is one of the most commonly used processes in web development. It helps with easier management during the development & design process. Apart from the management, templating helps with keeping the visual consistency.

Craft CMS comes with a cool templating engine — Twig. And we love to use macros to work on redundant parts while working on a Craft CMS project. Macros can be compared to ‘functions’ in PHP also known as DRY templating in other languages. We usually use it to generate markups that have slight final variations in the implementation.

To simplify your code you must first make a visual hierarchy of the page you’re working on. That way you can determine the components you’re going to need. Make macros for those components in the twig templating engine.

Macro implementations can be changed based on the parameters passed to it. For instance footers, dates, images and other media are a recurring part of a website. You can make macros for these components.

Skeleton of Twig Macro

{% macro coolMacroName (parameter 1,…..) %} {content of macro goes here} {% endmacro %}

To call the macro – {% import ‘_macroFilename’ as ‘macroVariable’ %} {{ macrovariable.coolMacroName(parameter1, parameter2,….) }}

The best practice is to add the relevant macros to a file and then call the file as a variable. Use the variable to call the macro at the places you need.

The first Macro we use often is-

Macro for responsive image component in Craft CMS

You can reduce and automate a lot of work which goes in responsive image formatting. Utilize Craft’s ‘Image transforms’ with a twig for images and define your transform macros in it. You will also have to define different types of macros for different image formatting needs.

A macro for Device-pixel ratio adaptable fixed size images and other one for variable size responsive images. Also add an internal class to call it inside your twig image file for additional attributes.

Macro for video component in Craft CMS

Videos are an integral part of every website, so making a twig component for it seems practical, otherwise you will spend your precious time writing and tweaking html code for videos.

In the macro define the logic of the video component. The file should have proper information about the component, the parameters which are accepted, the value each parameter requires, and whether the parameter is optional or not. You also need to mention, what the arrays and objects are made of because without that information you yourself and other developers won’t know, what information can/must or cannot be passed while calling the component.

Making macros for date formatting in Craft CMS

Dates might look like a trivial part of a template but it gets tedious and complex when you have to define its format in every other template.

You can contain different modifiable date formats in a macro. It saves you the effort of having to define it time and again and maintaining consistency all along. Short or long, just define the format in a macro and call it wherever you need it.

Reduce repeated reference of paths in Craft CMS

Include tag in twig allows you to call a template within a template. Each one you make gets stored in /templates/ folder by default, even your include templates.

You can call these partial templates separately followed by the same path or make a macro instead to reduce the repeated reference of path.

To achieve code consistency, store your ‘include’ templates separately. So that you can call the include templates within the macro. You can also call your ‘include templates’ from multiple locations.

Final words

That’s pretty much it. Apart from few other variations, creating macros for page components is a good and effective way to reduce the redundancy and complexity of the code. You can always go through this detailed video for macros here.

We’ve been experimenting with several DRY techniques ourselves. It improves the speed of our work cycle.

How are you using Twig & its components? If you need help with your Craft CMS project, connect with us right away.

Craft Vs Perch: A Clash Of Customizable CMSs

In our earlier blogs we’ve favoured Craft CMS heavily because of its ‘content first’ philosophy. Perch also majorly focuses on the content but with functionality shredded down to the absolute basics. It’s so minimalistic and that it is considered to be appropriate for small-scale projects only. Anyways, Perch has its perks as compared to conventional CMSs. Let’s put it to the test against the reigning champion, Craft CMS.

Feature comparison of Craft & Perch

Craft is loaded with crucial features, vis-a-vis:

Live Preview

Craft allows you to review the edits as you’re making them in a split screen window mode.

Matrix

Gives you the full control of your content, from layout and placement to the order.

Localization

You can create locales for the desired language and enable with just a click.

One-click updates

Simply update everything with one click from the control panel. The updater even notifies you according to the nature of the update; whether it’s incremental or critical.

Built from scratch

Craft CMS team clearly states that we don’t make any assumptions about your content. You get full control of your website and you can craft it the way you want. On the other hand, Perch has the following features to offer:

Preview

You get to see the changes only after when they are saved in the draft. A bit old fashioned to be honest but it goes with Perch’s tagline of ‘a very little CMS’

Custom Fields

The feature lets you create custom fields throughout the page.

Localization

Perch lets you localize your webpages by creating separate pages or duplicating regions for each language.

Updates

Updating in Perch is a bit cumbersome. You need to replace the old files with the new ones.

Retrofit or build from scratch

You can retrofit an existing website or build a minimal website from scratch.

Documentation comparison of Craft & Perch

Documentation is a crucial part of a CMS. It is important to define the features and inner workings of a CMS so that the new users know how to use it. It’s a map for the CMS users. Documentation, if not done properly, might mislead your users. There is nothing more off-putting than lack of documentation. Users are trying to find their way around the new CMS and if there is no good map, they’ll probably get lost and bounce-off faster than light from a mirror.

Craft

As far as the documentation is concerned Craft excels at it. You will immediately find everything you’re looking for. From update logs and feature definitions to essential how tos; Craft’s documentation has got it all.

Perch

Being the older CMS of the two, extra years in development hasn’t added much in favour of Perch CMS. Perch documentation is enough to get a hold of the basics but it disappoints when you’re half-way into the development process. Especially when you’re trying to give additional functionalities to your CMS with add-ons.

Community Support comparison of Craft & Perch

Documentation can only do so much, the real knowledge and solutions are derived from the dedicated communities formed around the CMS. The community makes up for the lack of documentation and helps you solve on-site issues.

Craft

Craft has a proactive community of dedicated developers and users that help to keep Craft as current as it can be. The Craft community just keeps growing as more people fall in love with the CMS.

Perch

Perch doesn’t aim to be a big CMS and hence it remains that way with 0.1% of the market share. It has a simple and functional CMS to offer but it’s not backed by convenient documentation and a good community support.
  • Perch Slack channel is no longer active
  • 3725 followers on Twitter
  • 615 fans on Facebook

User Interface comparison of Craft & Perch

User interface determines how you interact with the content. Both the CMSs provide you with a dashboard to edit and manipulate your content using the interface. The simpler the interface the lesser the struggle to understand it.

Craft

Craft focuses on providing powerful and bespoke results. The interface hence is equipped with essential functionalities to handle large amounts of data gracefully. Although it is considered to be highly-technical and dev-friendly, Craft CMS offers a conveniently easy drag and drop interface for layout design.

Perch

Perch on the other hand stays true to its principle of being basic with the user interface too. It is comprehensive and doesn’t require extensive technical expertise. However to people who want more control over their content it is basically under equipped.

Development Cycle comparison of Craft & Perch

Craft uses an unconventional and complex data structure, hence the bigger learning curve. Singles, structures, and channels as data structures give you unmatched control and editing capabilities. For front-end development Craft utilizes Twig templating engine for advanced templates and data manipulation. Perch uses PHP functions for the development as compared to Twig in Craft. The content structure is pretty straight forward, it features pages, regions, and shared regions for data manipulation. For the added functionality of reusing content throughout the page you need to upgrade to larger version of Perch which is Perch Runway. Both the CMSs have their benefits but it is rather important and practical to go with the CMS which is flexible and future-proof. While Perch is a straight forward CMS which doesn’t try too hard to be something it’s not, it is only good for small projects and businesses with a tight budget. On the contrary, Craft CMS provides necessary functionalities paired with high-end security. It is a capable and viable choice for both developers and content editors. Looking at the security track record of Craft we’ve always chosen Craft CMS over every other CMS for our clients. In case you are confused about how