Search code examples
phpsymfonytwig

Twig - Replacing double quotation in an href inside data-description


I'm having trouble building out a data-description which will contain an href. The stored value contains double quotation marks, which obviously causes issues so I'd like to replace the double quotation marks with single quotes. This seems like it would be very simple to do but my replace does not seem to be working.

<img src="#" data-description="{{ photo.description|replace({'%"%': "'"}) }}"/>

The description is:

<p>Cool description blah. <a href="http://www.google.com">Google</a></p>

The result of this on the page ends up being:

<img src="# data-description="<p>Cool description blah. <a href=\&quot;http://www.google.com\&quot;>Google</a></p>" style="width: 345px; height: 229px;">

The double quotes are not replaced and the are now escaped instead.

If I try raw:

<img src="#" data-description="{{ photo.description|replace({'%"%': "'"}) }}"/>

Everything breaks and ends up looking like this:

<img src="#" data-description="<p>Cool description blah. <a href=\" http:="" www.google.com\"="" style="width: 345px; height: 229px;">
Google
<p></p>
"/&gt;

My primary question is, why aren't I able to replace the double quotes?


Solution

  • The problem seem related to the replace pattern you specified: you don't need to use the % character (probably the doc example counfuse a bit because the example use it as paceholder).

    So try simple this:

    <img src="#" data-description="{{ desc|replace({'"':'\''})|raw }}"/>
    

    Here a working example.