我应该如何有条件地渲染图标?

How should I go about rendering an icon conditionally?

问题描述:我想在已单击的列名旁边显示一个图标(来自 Semantic UI)。用户将单击此列以按该列对列表进行排序。

基本上,我正在处理一个包含列的电影列表 - 标题、评级、描述和发行日期。我已将 'Title' 和 'Release Date' 制作成可点击的链接,点击后,电影列表按 Title/Release 日期排序。

我的routes.rb文件:

Rails.application.routes.draw do
    root 'movies#index' 
           
    resources :movies 
end    

在我的 index.html.erb 文件中,我将标题和发布日期设为:

<%= link_to "Title", movies_path(sort: "title") %>
<%= link_to "Release Date", movies_path(sort: "release_date") %>

在我的 movies_controller.rb 中,我正在获取所有电影条目并在 order - Movie.all.order(params[:sort]) 的帮助下对它们进行排序。

一切正常。

接下来我想做的是在已单击的列名称旁边显示一个图标 (<i class="chevron up icon"></i>)。

我的想法是将<i class=""></i>留空,然后在movies_controller#index里面设置一个变量到chevron up icon,然后根据params[:sort]有条件地设置它,然后在视图中渲染它。但我认为这不是正确的方法,因为它不适用于标题和发布日期。

我正在寻找正确的方法来做到这一点。我会使用其中一个帮助程序文件 - application_helper.rbmovies_helper.rb?有人请向我解释逻辑。正如你现在应该能够说的那样,我是 Rails 的初学者,请原谅我的无知。

在 ERB 中,您可以通过以下方式解决此问题:

<%= link_to movies_path(sort: "title") do  %>
  Title
  <% if params[:sort] == "title" %>
    <i class="chevron up icon"></i>
  <% end %>
<% end %>

<%= link_to movies_path(sort: "release_date") do  %>
  Release Date
  <% if params[:sort] == "release_date" %>
    <i class="chevron up icon"></i>
  <% end %>
<% end %>

link_to 助手为元素内容采用可选块,可以用来代替字符串。

更简洁的解决方案是编写辅助方法:

# app/helpers/movies_helper.rb
module MoviesHelper
  # Gives a link for columns in a table that can be used to sort the movies
  # will add an icon if the link is "active"
  # @param name String
  # @param column [Symbol|String]
  # @example
  #   sortable_link_to_movies("Critic rating", "critic_rating")
  # @return [ActiveSupport::SafeBuffer]
  #   <a href="/movies?sort=critic_rating>Critic rating</a>
  #   <a href="/movies?sort=critic_rating>Critic rating <i class="chevron up icon"></i></a>
  def sortable_link_to_movies(name, column, **opts)
    link_to movies_path(sort: "title", **opts) do
      # concat is needed to write to the text buffer of the helper
      concat name
      if column.to_s == params[:sort]
        concat tag.i class: "chevron up icon" 
      end
    end
  end
end
<%= sortable_link_to_movies "Title", :title %>
<%= sortable_link_to_movies "Release Date", :release_date %>

这让您可以单独测试该方法。