Is it possible to disable the ampersand encoding when rendering <div {{ attributes }}> in a hook (preferred) or Twig?

Drupal by default escapes ampersands & into &amp;. This usually is a good thing, but I've the edge case where I need to render one-off TailwindCSS class names like [&_.child-of-this-div]:text-red. Looks weird, but is actually a completely valid CSS class name.

But due the ampersand encoding, the rendered output now looks like <div class="[&amp;_.child-of-this-div]:text-red">, which by CSS rules is now a completely different class name, and Tailwind's parser therefore no longer "sees" the real class name [&_.child-of-this-div]:text-red.

Already tried, did not work:

  • Backslash escaping [\&_.child-of-this-div]:text-red (still incorrect output)
  • using CSS symbol encoding [\000026_.child-of-this-div]:text-red (does not work with Tailwind's parser).
  • using the raw filter: {{ attributes|raw }} (still incorrect output)

1 Answer 1


The combination of both, |replace and |raw, does remove the encoding.

<div {{ attributes|replace({'&amp;': '&'})|raw }}>

I needed data-attributes to remain untouched, the closest I got so far is

<div class="{{ attributes.class|replace({'&amp;': '&'})|raw }}" {{ attributes|without('class') }}>

but this is tedious and unsafe.

I'm still looking for something that does not use |raw, so I leave the question open.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.