Introduction

Tailwind Merge Classes is a Drupal module for users working with Tailwind CSS in a component-based syntax. It adds a Twig filter, |tw_merge, that merges Tailwind CSS classes, resolves conflicts automatically, and keeps the class list clean. The older tw_merge() and tw_merge_as_array() functions are still available for existing templates.

If you are interested in more details, this video explains the original JavaScript utility tailwind-merge that this module's logic is based on.

Using the Filter

  • {{ 'p-4 bg-white p-2'|tw_merge }} outputs class="bg-white"
  • {{ ['p-4', 'bg-white', 'p-2']|tw_merge }} outputs class="bg-white"
  • {{ attributes.addClass(['p-4', 'bg-white', 'p-2']|tw_merge).removeClass('p-2') }} outputs class="bg-white"

Legacy Functions

Sites that already use the tw_merge() and tw_merge_as_array() Twig functions can keep using them. They are still available and were not removed, so existing templates keep working without changes. The recommended approach is the tw_merge filter: use it in new templates, and switch existing ones when convenient.

The functions need you to choose the return type, because a string and an array are used in different places:

  • tw_merge(classes) or tw_merge(classes, as='string'): returns a string, for printing inside class="...". A string can't be used with removeClass(), because Drupal stores it as a single class.
  • tw_merge(classes, as='array'): returns an array, for addClass() and removeClass(), where each class must be a separate item.
  • tw_merge_as_array(classes): the earlier way to get an array, which works the same as as='array'.

The new filter doesn't need this choice. It returns a value that works both when printed and inside addClass() and removeClass(), so you can just use |tw_merge with the filter syntax everywhere.

Each function and its filter equivalent are listed in the legacy guide for your version:

Guides

Version 2.x (Tailwind CSS 4.x)

Version 1.x (Tailwind CSS 3.x)

Class Prefix (Optional)

If your Tailwind setup uses a class prefix, set it at Configuration » Development » Tailwind Merge - Add Prefix (/admin/config/development/tailwind-merge):

  • Version 2.x: enter the value from prefix(tw), for example tw, for classes like tw:flex.
  • Version 1.x: enter the value from tailwind.config.js exactly, for example tw-, for classes like tw-flex.

Version Support

  • Module version 1.x: Compatible only with Tailwind CSS 3.x
  • Module version 2.x: Compatible only with Tailwind CSS 4.x

Third-Party Libraries

This module depends on different PHP packages to handle merging of Tailwind CSS classes for each Tailwind version.

Both PHP packages require PHP 8.1 and above.

Project information

Releases