I'm trying to build a block helper but I cant seem to figure out a way to get access to current_page? from within the class.
My helper file looks like this:
class NavList
include ActionView::Helpers::TagHelper
include ActionView::Helpers::UrlHelper
def header(title)
content_tag :li, title, class: 'nav-header'
end
def link(title, path, opts={})
content_tag :li, link_to(title, path), class: opts[:class]
end
end
def nav_list(&block)
new_block = Proc.new do
helper = NavList.new
block.call(helper)
end
content_tag :ul, capture(&new_block), class: 'nav nav-list'
end
and i can use the helper via
<%= nav_list do |nl| %>
<%= nl.header 'Location' %>
<%= nl.link 'Basic Information', url_for(@department), class: current_page?(@departments) ? 'active' : '' %>
<%= nl.link 'Employees', department_users_path(@department) %>
<% end %>
But what I would like to do is to not have to constantly take on that active class. So I would like to do something like this
def link(title, path, opts={})
css_class = 'inactive'
css_class = 'active' if current_page?(path)
content_tag :li, link_to(title, path), class: opts[:class]
end
But i cant find a way to use current_page? from within the NavList class. It compains about a request method not found
According to the documentation the current_page? method requires the request object, maybe you could try passing the request object directly into the link method.
def link(title, path, request, opts={})
css_class = 'inactive'
css_class = 'active' if current_page?(path)
content_tag :li, link_to(title, path), class: opts[:class]
end
<%= nl.link 'Employees', department_users_path(@department), request %>
Not sure if there's a better way though
class NavList
attr_accessor :request
include ActionView::Helpers::TagHelper
include ActionView::Helpers::UrlHelper
def header(title)
content_tag :li, title, class: 'nav-header'
end
def link(title, path, opts={class: ''})
opts[:class] = "#{opts[:class]} active" if current_page?(path)
content_tag :li, link_to(title, path), class: opts[:class]
end
end
def nav_list(&block)
new_block = Proc.new do
helper = NavList.new
helper.request = request
block.call(helper)
end
content_tag :ul, capture(&new_block), class: 'nav nav-list'
end
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.