How to Wrap Link_To Around Some HTML Ruby Code

How do I wrap link_to around some html ruby code?

link_to takes a block of code ( >= Rails 2.2) which it will use as the body of the tag.

So, you do

<%= link_to(@album) do %>
html-code-here
<% end %>

But I'm quite sure that to nest a div inside a a tag is not valid HTML.

EDIT: Added = character per Amin Ariana's comment below.

Wrapping Link_to around contents in Rails

Are you looking at the Inspector, or the actual generated code? If the former, it's probably what the browser is interpreting your HTML as, rather than what it actually is in the source code.

The reason it's wonky is because you can't put an li into an anchor in that way; the only thing a ul or ol is allowed to contain is an li. Change the code to this, and it should work:

 <li>
<%= link_to project_path(remix) do %>
<div class="remix-list-image"><%=link_to image_tag(remix.default_image.image_path_url(:preview), :class=>"img-polaroid"), project_path(remix) %></div>
<div class="remix-list-title"><%=link_to remix.title, project_path(remix) %> by <%= link_to remix.author, user_path(remix.user) %></div>
<% end %>
</li>

Use link_to helper wrap some HTML

per the rails documentation:

<%= link_to({:controller => "user" , :action => "resume" }, :class => is_active?("index")) do %>

<li class="usidebar-index">index</li>

<% end %>

rails - wrap HTML element around text of link_to() in ruby code without disabling all escaping

Use content_tag:

link_to(content_tag(:bdi, user_controlled_text), destination)

# or with a block
link_to(destination) do
content_tag(:bdi, user_controlled_text)
end

Rails wrap link_to on html code based on condition

With link_to_if the block to pass is actually the else. Have a closer look at the documentation you linked to.

Anyway, using link_to_if won't solve your dryness issue either. What you want to do is using capture to assign the common html to a variable:

<% content = capture do %>
<p>Some html here</p>
<% end %>

<% if condition? %>
<%= link_to bla_bla_path do %>
<%= content %>
<% end %>
<% else %>
<%= content %>
<% end %>

ruby on rails wrap block of code in link_to

You need to give only path with link_to when using the block.

<%= link_to({:controller =>  "events", :action => "search", :category => @favorites[0].name}) do %>
<div>
<%= @favorites[0].name %>
</div>
<%end%>

link_to tag not including all divs

Two things:

  • You are using link_to inside another call to link_to. That is probably not what you want.
  • The result of a block will be what you return from a block, normally the last line. Take a look at this question for a solution.

How to link_to ruby code and text in Rails

Almost!

Interpolation is what you want. The ruby goes in the #{ }.

<%= link_to "#{post.comments.count} comments", post %>


Related Topics



Leave a reply



Submit