I'm trying to add a "current" class to the following set of links based on if there is an "order" param in the URL. (ie. example.com/photos?order=views). I need some help refactoring this so it's not so burly.
<% unless params[:order] != 'created_at' %>
<%= link_to "Recently Posted", photos_path, :class => 'current' %>
<% else %>
<%= link_to "Recently Posted", photos_path %>
<% end %>
<span class="pipe">|</span>
<% unless params[:order] != 'comments' %>
<%= link_to "Most Commented", photos_path + "?order=comments", :class => 'current' %>
<% else %>
<开发者_如何学编程;%= link_to "Most Commented", photos_path + "?order=comments" %>
<% end %>
<span class="pipe">|</span>
<% unless params[:order] != 'views' %>
<%= link_to "Most Viewed", photos_path + "?order=views", :class => 'current' %>
<% else %>
<%= link_to "Most Viewed", photos_path + "?order=views" %>
<% end %>
For example you can use helper:
<%= link_to_photos_with_order 'created_at', "Recently Posted" %>
<span class="pipe">|</span>
<%= link_to_photos_with_order 'comments', "Most Commented" %>
<span class="pipe">|</span>
<%= link_to_photos_with_order 'views', "Most Viewed" %>
def link_to_photos_with_order order_by, title
url = photos_path(:order => (order_by != 'created_at' ? order_by : nil))
unless params[:order] != order_by
link_to title, url, :class => 'current'
else
link_to title, url
end
end
Another way is to use hash with order_by => title but it is uglier
Extract the logic into a helper:
def link_to_ordering(params, ordering, title)
css_class = params[:order] == ordering ? 'current' : ''
link_to(title, photos_path(:order => ordering), :class => css_class)
end
Then just call e.g.:
<%= link_to_ordering(params, "Most Commented", "comments") %>
in your views.
精彩评论