1

Is there an easy way to disable the HTML entity encoding of CSS class names?

When I create CSS classes with ampersands or the "larger than" symbol (which might look strange but is technically valid in CSS classes) like this

{% set my_attribute_object = create_attribute({'class': '[&>span]:text-red'}) %}
<div {{ my_attribute_object }}>
  I'm text in <span>red</span> color.
</div>

it renders escaped entities like

<div class="[&amp;&gt;span]:text-red">
  I'm text in <span>red</span> color.
</div>

which then breaks the TailwindCSS JIT compiler, who expects real ampersands in the HTML source.

I could do something like this

<div {{ my_attribute_object|replace({'&amp;': '&', '&gt;': '>'})|raw }}>

but I need to render attribute objects in Twig templates all the time, and adding this all the time is ugly and tedious. I'm looking for a better way (maybe a preprocess function that does the |replace|raw automatically for every attribute?)

3
  • You need to extend the Attribute object overriding createAttributeValue to not convert HTML markup but to put it in a AttributeMarkup object (that you also need to extend from AttributeValueBase and adjust the magic string method). Then use the new Attribute class in preprocess.
    – 4uk4
    Nov 10, 2023 at 11:04
  • or to be more precise not only in preprocess, whenever you want to add attributes with HTML markup first convert the existing attributes $attributes = new MyMarkupAttribute($attributes);
    – 4uk4
    Nov 10, 2023 at 11:22
  • I wished attribute objects would be a symfony service... I guess I've to dig through all my modules :/
    – Hudri
    Nov 10, 2023 at 11:26

0

Your Answer

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

Browse other questions tagged or ask your own question.