Tidy up .html.erb output
My application layout has a login/logout link that displays depending on whether you are signed in or not:
<% if signed_in? %>
<%= link_to "Sign out", signout_path, :method => :delete %>
<% else %>
<%= link_to "Sign in", signin_path %>
<% end %>
This works fine, but seems really untidy and verbose. How can I output the appropriate link_to w开发者_StackOverflow中文版ithout so many <%...%> brackets?
I'd go with HAML, but if you don't want to use HAML, you could use a ternary operator:
<%= signed_in? ? link_to( 'Sign Out', signout_path, :method => :delete ) : link_to( 'Sign In', signin_path ) %>
Use HAML ;)
- if signed_in?
= link_to "Sign out", signout_path, :method => :delete
- else
= link_to "Sign in", signin_path
You could use the concat helper: (ActionView::Helpers::TextHelper)
<%
if signed_in?
concat link_to( "Sign out", signout_path, :method => :delete )
else
concat link_to( "Sign in", signin_path )
end
%>
Though in the rails api they prefer the <% %> syntax....
Try adding a - (dash) to your closing tag, like so:
<% if signed_in? -%>
<%= link_to "Sign out", signout_path, :method => :delete -%>
<% else -%>
<%= link_to "Sign in", signin_path -%>
<% end -%>
From: http://www.plexusweb.com/staff/travis/blog/post/117/Rails-inline-ERb-effects-on-HTML-structure
Edit; My bad, thought is was about formatting the HTML output (newlines etc.)
With 2 open-close brackets you could do it like this:
<%= link_to( "Sign out", signout_path, :method => :delete ) if signed_in? %>
<%= link_to( "Sign in", signin_path) if !signed_in? %>
精彩评论