简体   繁体   中英

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 without so many <%...%> brackets?

我会选择HAML,但是如果你不想使用HAML,你可以使用三元运算符

<%= 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? %>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM