我正在尝试根据URL中是否存在“order”参数,将“当前”类添加到以下链接集。 (即example.com/photos?order=views)。我需要一些帮助重构这一点,所以它不是那么魁梧。
<% 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 %>
答案 0 :(得分:4)
例如,您可以使用帮助程序:
<%= 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
另一种方法是使用带有order_by =&gt;的哈希值标题,但它更丑陋
答案 1 :(得分:1)
将逻辑提取到帮助器中:
def link_to_ordering(params, ordering, title)
css_class = params[:order] == ordering ? 'current' : ''
link_to(title, photos_path(:order => ordering), :class => css_class)
end
然后只需拨打电话:
<%= link_to_ordering(params, "Most Commented", "comments") %>
在您的观点中。