首页 > 解决方案 > 在 Rails 中根据 url 应用锚标签

问题描述

我正在使用一个模板化了一堆网站的 CMS,我需要对这些页面应用跳过导航。

因此,在他们绘制的默认模板中,我有以下内容:

<a href="#some-content">Skip to Some Content</a>
<a href="#other-content">Skip to Other Content</a>
<a href="#yes-content">Skip to Yes Content</a>

然后在 CMS 中,我将 id 应用于内容

<div id="some-content">Stuff</div>

我要做的只是在实际位于该页面上时应用锚标记。

因此,例如,如果我在“其他内容”页面上,它不会显示所有锚标记。

我的想法是以下帮手:

module ApplicationHelper
  def current_url(url)
   url = request.path_info
   if url.include?('other')
     content_tag :a, href: '#other-content'
   end
  end
end

然后我将锚标签替换为

<%= current_url %>

并且...ActionView::Template::Error(参数数量错误(给定 0,预期为 1))

我的助手有问题吗?

我还在我的助手中尝试了以下相同的结果:

def original_url
 base_url + original_fullpath
end

def anchor_update
  if original_url.include?('services')
    content_tag :a, href: '#services'
  end
end

标签: ruby-on-rails

解决方案


ActionView::Template::Error(参数数量错误(给定 0,预期为 1))

好吧,current_url(url)需要一个参数,并且您将其称为<%= current_url %> 没有任何导致该错误的参数。从它的外观来看,您应该在分配url 显式时定义不带任何参数的方法。

module ApplicationHelper
  def current_url
   url = request.path_info
   if url.include?('other')
     content_tag :a, href: '#other-content'
   end
  end
end

推荐阅读