【问题标题】:How do i add an active class to a dynamic link?如何将活动类添加到动态链接?
【发布时间】:2016-02-20 23:00:55
【问题描述】:

我有一个包含帖子列表的侧边栏。我需要侧边栏上的相应帖子才能有一个活跃的课程。我目前所拥有的不起作用,那么最好的方法是什么?

def is_active?(path)
  current_page?(path) ? "active" : ""
end

<% @posts.each do |post| %>  
    <%= link_to post.title, post, class: is_active?(posts_path) %>  
<% end %>

【问题讨论】:

  • is_active?(posts_path) 检查并返回什么?
  • 它什么也没返回我只是得到一个空白类。
  • 试试class: [(:active if is_active?(posts_path))]
  • Ruby 方法以 ? 结尾,按惯例返回布尔值。因此,您的 is_active?(posts_path) 将返回 true 或 false,我什至不想知道 Ruby 如何将其解释为字符串...
  • 能把is_active?的代码发一下吗?

标签: ruby-on-rails ruby ruby-on-rails-4


【解决方案1】:

正如我在评论中所说,以? 结尾的方法应该返回一个布尔值。如果您决定违反约定,这将使我们更加困难。

我建议您实际使用active_link_to,就像question 中解释的那样。

但主要问题是您没有为每个帖子正确生成 URL:

is_active?(posts_path)

posts_path 是索引的路径,而不是单个帖子资源。你应该使用类似post_path(post)

你想做这样的事情:

首先你的is_active? 方法,因为它有一个?应该返回一个布尔值

def is_active?(path)
  current_page?(path)
end

那么就可以这样使用了(需要使用post_path(post)helper获取帖子的URL)

<% @posts.each do |post| %>  
    <%= link_to post.title, post, class: ('active' if is_active?(post_path(post))) %>  
<% end %>

编辑:因为 is_active?和 current_page 一样吗?您应该简单地将 is_active? 代码替换为别名声明

alias :is_active? current_page? 

【讨论】:

  • 这会在我的所有帖子中添加一个活动类。
  • @EliteViper7777 这意味着您的 is_active?() 方法有问题。请出示其代码。
  • def is_active?(path) current_page?(path) ? "活动" : "" 结束
  • 您的 is_active? 不返回布尔值。这违反了 Ruby 约定以及失败的原因。
  • 我更新了答案。基本上问题是你使用posts_path 而不是post_path(post)
【解决方案2】:

几年前我不得不开发这样的解决方案。我实现了以下作为辅助方法来检测活动链接。请注意,这不是我认为的最佳解决方案。我必须提供一个完整的网址。随意编辑代码以使用路径或参数哈希代替。

# Returns true or false if the page is displayed that belongs to the given url.
def link_selected?(url)
  request_method = request.method.to_sym
  begin
    url_params = Revolution::Application.routes.recognize_path(
      url, {:method=>request_method}
    )
  rescue Exception => e
    {}
  end
  begin
    request_params = Revolution::Application.routes.recognize_path(
      request.url, {:method=>request_method}
    )
  rescue
    {}
  end  
  return true if url_params == request_params
  return false
end

def is_active?(url)
  return link_selected?(url) ? 'active' : nil
end

【讨论】:

    猜你喜欢
    • 2010-12-29
    • 2013-08-15
    • 2016-03-28
    • 1970-01-01
    • 2017-05-16
    • 2017-11-26
    • 1970-01-01
    • 1970-01-01
    • 2017-11-18
    相关资源
    最近更新 更多