很简单了。。一个 helper 的例子,代码有点乱
def output_cities()
p = request.query_parameters.to_hash
p.delete "city"
html = "<li>"+link_to("全部", providers_path(p), :class => "icon-all #{"cur" if params[:city].blank?}")+"</li>"
CITIES.each do |k, v|
html<< "<li>"+link_to(v[0], providers_path(p.merge("city" => k)), :class => "#{v[1]} #{"cur" if params[:city] == k}")+"</li>"
end
html.html_safe
end
@Rei 我曾经的实现是直接往 output_buffer 里写,这样呢? 如果要是这样不合适的话,那就采用 partial view 的方式了,要不 html 会比较乱
city_helper.rb
def render_cities
render :partial => "city_options"
end
def render_option_of_total_city(city)
css_class_name ||= ""
css_class_name = "cur" if city.blank?
link_to("全部", providers_path(p), :class => "icon-al#{css_class_name}")
end
def render_option_of_single_city(k,v,city)
css_class_name ||= ""
css_class_name = "cur" if city == k
link_to(v[0], providers_path(p.merge("city" => k)), :class => "#{v[1]} css_class_name")
end
_city_options.html.erb
<li> <%= render_option_of_total_city(params[:city]) %> </li>
<%= content_tag_for(:li, CITIES) do |k,v|%>
<li> <%= render_option_of_single_city(k,v, (params[:city]) ) %> </li>
<% end %>
不保證會動...但是我的話,要兼顧維護性和效能我會這樣寫...
" "
字串裡再作一次邏輯判斷