Dynamic CMS Styling in Elements: Injecting Tags as CSS Classes via Twig

I am currently in the process of rebuilding my website, cycleruncode.club. My objective is to unify several disparate journals into a single CMS collection and use tags (e.g., cycle, run, code) to trigger discipline-specific styling, such as unique border colours and typography for each activity.

Initially, I struggled because the CMS tags weren’t being utilised in the rendered HTML, leaving them missing from the class list where I had assumed they would be available for CSS targeting.

How I managed to solved it: After some experimentation, I discovered that the Advanced → CSS Classes field in the component inspector actually supports Twig expressions. By selecting the ‘Flex Link’ component within my CMS collection and entering the following into the Classes field:

lab-log-link {{item.tags|join(' ')}}

I was able to force the CMS to output the tags directly into the HTML class list. This allowed me to write global CSS rules targeting .lab-log-link.cycle and .lab-log-link.run to achieve the desired aesthetic.

Seeking Confirmation: Whilst this method is working brilliantly, I wanted to confirm with the community:

  1. Is injecting Twig directly into the ‘CSS Classes’ inspector field considered best practice for dynamic styling in Elements?

  2. Is there a more formal way to add custom attributes (such as data-discipline) to components that I might have overlooked in the interface?

I would be grateful for any insights on whether this is the intended architectural approach for data-driven styling.

We don’t have any best practices set for this type of thing. However, the way you’ve achieved it is definitely valid :slight_smile:

Not currently. If the component is a link, you can add data- attributes via the custom attributes in the link inspector. Like so:

We do intend to add additional components to the CMS that might help with this type of scenario — perhaps a CMS Conditional component that would allow you to conditionally display content based on the tags.

In short: what you’ve done is a great use of the current components and twig templating system available to you :slight_smile: