0

我正在做 Ryan Bates可排序表列截屏视频

如果该项目位于th标签内,并且如果选择了该项目,我想应用一种样式,我该怎么做?

瑞安屏幕演员代码:

控制器

class ProductsController < ApplicationController
  helper_method :sort_column, :sort_direction

  def index
    @products = Product.order(sort_column + " " + sort_direction)
  end

  # ...

  private

  def sort_column
    Product.column_names.include?(params[:sort]) ? params[:sort] : "name"
  end

  def sort_direction
    %w[asc desc].include?(params[:direction]) ? params[:direction] : "asc"
  end
end

帮手

def sortable(column, title = nil)
  title ||= column.titleize
  css_class = column == sort_column ? "current #{sort_direction}" : nil
  direction = column == sort_column && sort_direction == "asc" ? "desc" : "asc"
  link_to title, {:sort => column, :direction => direction}, {:class => css_class}
end

index.html.erb

<tr>
  <th><%= sortable "name" %></th>
  <th><%= sortable "price" %></th>
  <th><%= sortable "released_at", "Released" %></th>
</tr>

概念

<tr>
  <th class=<%= @selected %> ><%= sortable "name" %></th>
  <th class=<%= @selected %> ><%= sortable "price" %></th>
  <th class=<%= @selected %> ><%= sortable "released_at", "Released" %></th>
</tr>

CSS

.pretty th .current {
  padding-right: 12px;
  background-repeat: no-repeat;
  background-position: right center;
}

.pretty th .asc {
  background-image: url(/images/up_arrow.gif);
}

.pretty th .desc {
  background-image: url(/images/down_arrow.gif);
}
4

1 回答 1

1

我不确定什么是最好的约定,但我认为这样的事情会起作用:

<tr>
  <%= stylized_th(@selected) { sortable "name" } %>
  <%= stylized_th(@selected) { sortable "price" } %>
  <%= stylized_th(@selected) { sortable "released_at", "Released" } %>
</tr>

使用额外的助手:

def stylized_th(selected, &block)
  content = capture(&block)
  content_tag(:th, content, class: selected)
end

您可以在其中放置一些逻辑,以根据selected. 如果您不想上课,请使用nil.

我受到这个 RailsCast 的启发: http: //railscasts.com/episodes/208-erb-blocks-in-rails-3

我希望它有所帮助。

于 2013-02-12T05:15:44.023 回答