views:

46

answers:

2

I'm a bit of a Ruby on Rails amateur, and I am trying to nest a div tag inside of an anchor tag in rails. I can make it work, but the resulting code I have written is terrible and is certainly NOT the rails way.

Here is an example of what I am trying to accomplish in HTML:

<a href="tell-a-friend">
<div id="tellafriend">
    <strong>Strength in Numbers.</strong><br />
    Suggest a friend or colleague to participate in this survey.
</div>
</a>

Here is what I came up with to do it in ERB:

<%= link_to content_tag(:div, 
    content_tag(:strong, 'Add your labor rates now.') + 
    content_tag(:br, '') + ' We are counting on you.', :id => 'participate'), 
participate_path %>

Or here I mixed some HTML and ERB:

<%= link_to '<div id="results">
    <strong>See the results.</strong><br />
    Knowledge is power.
</div>'.html_safe, results_path %>

Both of my solutions seem very ugly... but moving it into a helper didn't seem like the right thing to do, given that the content of the DIV changes and that I am only displaying 3 of these on one page.

So if anyone is aware of a better way to do this, I am interested! Any combination of HTML, ERB and HAML is ok by me.

+1  A: 

Links work as blocks:

<% link_to '', my_path do %>
  <div></div>
<% end %>
Jarrod
Wow, I can't believe I didn't know that. /cryUpdate:Just tested it in my rails3 beta4 app... needed a minor tweak to make it work. Essentially <% link_to my_path do %> ... <% end %>
Scott S.
Yeah, sorry about that. The '' part of the link_to shouldn't be there at all in a block. And Rails 3 may use <%= instead of <% in opening line.
Jarrod
+1  A: 

FYI: An ANCHOR surrounding a DIV is not legal in HTML 4.01 Transitional (but it is in HTML5?) so make sure that you use the correct doc-type and test on the target browser(s)!

<head>
<title>a</title>
</head>
<body>
<div>
<a href="www.google.com">
<div>test</div>
</a>
</div>
</body>
</html>

You can run this at W3C Validator and change the DOCTYPE to see for which mode(s) this is valid. (Make sure to specify the encoding as well to get rid of the warning :-)

pst
Interesting, but this is a rails specific question.
Scott S.
You could also just put an empty anchor tag in front of the div.
Tomas Markauskas