Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dealing with quotes in html.erb

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?

like image 598
scientiffic Avatar asked Feb 12 '23 01:02

scientiffic


1 Answers

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.

like image 170
DiegoSalazar Avatar answered Feb 23 '23 08:02

DiegoSalazar