Currently I am using twig's replace filter to replace the tags:

{% set str = block.body | raw %}
{{ str | replace('<p>', '<p class="myClass" data-wow-duration="1s">') }}

But on output it's not outputting the actual tags but:

&lt;p class=&quot;myClass&quot; data-wow-duration=&quot;1s&quot;&gt;

How do I keep the tags as tags?


Use the raw filter on the replaced string (output), not block.body (input):

{% set str = block.body %}
{{ str | replace('<p>', '<p class="myClass" data-wow-duration="1s">') | raw }}

Also, some friendly advice: I'd like to point out that rewriting HTML in this way is pretty risky.

Shameless plug alert, but I wrote a plugin called Retcon HTML which lets you manipulate your HTML content using PHP's DOMDocument – a far safer approach :)

This is how you could achieve your specific goal using Retcon's Attr method:

{{ block.body | retconAttr( 'p', { 'class' : 'myClass', 'data-wow-duration' : '1s' } ) }}
  • I was wondering if there was something like this. Thank you! Final solution: {{ block.body | retconAttr( 'p', { 'class' : 'myClass anotherClass', 'data-wow-duration' : '1' } ) }} – Leah Apr 21 '15 at 1:28
  • No worries, happy it could help you out! – Mats Mikkel Rummelhoff Apr 21 '15 at 6:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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