I'm setting a data element of an image in my html.erb file:
<img src="<%=image%>" data-description="<%= auto_link(step.description)%>"/>
The issue is that there there are sometimes quotes in my step.description that interfere so that data-description is not set correctly, such as:
<img src="..." data-description="<pre><code class=" language-java"="" style="width: 193px; height: 257px; margin-left: -96.5px; margin-top: -128.5px; opacity: 1;">
How can I remove conflicting quotes in my erb file?
There's a helper method called j
or escape_javascript
that will escape quotes in a string and make it possible to add a string with quotes to an attribute on an element like you're trying to do. More info here
So, change your code to:
<img src="<%=image%>" data-description="<%=j auto_link(step.description)%>"/>
Just adding that j
will do it for any sort of string with quotes.
If you're also putting HTML inside an HTML attribute you will have to escape html too with the html_escape helper:
<img src="<%=image%>" data-description="<%=h j(auto_link(step.description))%>"/>
h
is short for html_escape
. That should escape the tags inside the attribute and not break your layout.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With