Rails 3: Why "link_to" gives wrong output?
In my view file开发者_如何学运维 I type the following:
<table>
<tr>
<td><%= link_to(tag(:div, {:class => "my_class"}), "my_address") %></td>
</tr>
</table>
The result is: (observed in Firebug)
<table>
<tbody>
<tr>
<td>
<a href="my_address"></a>
<div class="my_class"></div>
</td>
</tr>
</tbody>
</table>
Why the div
is not inside a
?
You should use content_tag
, not tag
.
<table>
<tr>
<td><%= link_to(content_tag(:div, { :class => "my_class" }), "my_address") %></td>
</tr>
</table>
Honestly, in this case I prefer to use a block.
<table>
<tr>
<td>
<%= link_to "my_address" do %>
<div class="my_class"></div>
<% end %>
</td>
</tr>
</table>
Rails doesn't perform any kind of HTML validation thus I didn't take into consideration the implication about valid/invalid HTML resulting from your code.
According to Is putting a div inside a anchor ever correct?, you can only place inline elements inside of an anchor. <div>
is a block element, so your code will not work. You'll need to use something like <span>
to wrap whatever data you intend to put in the anchor.
The first post does go on to say that HTML5 allows <a>
to contain blocks though, so if you are defining HTML5 as your doctype then we need to dig deeper.
You can't have div
inside a <a>
tag. Use <span>
or <p>
instead
You cannot put block elements inside inline elements. If you are trying to link the div, you should use this:
tag(:div, {:class => "my_class", :onclick => "my_address"})
Otherwise, use span
instead of div
精彩评论