spyderman4g63
spyderman4g63

Reputation: 4309

Why is rails html_safe method changing my html structure?

I'm passing a self-closing anchor tag with no text value, just a name:

<% test = '<h4><a name="139-01"/>test</h4>' %>

When I output the value it looks like this:

<h4><a name="139-01"/>test</h4>

Then I try to use .html_safe to output it as an html tag

<%= test.html_safe %>

The resulting code is:

<h4><a name="139-01">test</a></h4>

As you can see above the anchor tag was change from a self-closing tag to a tag that includes the text "test" for some reason. Does anyone know why this is occurring?

If I set the string to:

<% test = '<h4><a name="139-01"></a>test</h4>' %>

It works as expected:

<h4><a name="139-01"></a>test</h4>

The problem is that I don't have access to change the tag in the actual data.

Upvotes: 1

Views: 180

Answers (1)

spickermann
spickermann

Reputation: 106782

It is not Ruby on Rails changing your HTML.

A self-closing hyperlink simply is invalid HTML. And it is the browser that tries its best to parse and understand this invalid HTML and the browser adds the closing </a> tag where it thinks it makes the most sense.

Relevant in this context:

Upvotes: 4

Related Questions