method
current_page?
v8.1.1 -
Show latest stable
- Class:
ActionView::Helpers::UrlHelper
current_page?(options = nil, check_parameters: false, method: :get, **options_as_kwargs)public
True if the current request URI was generated by the given options.
Examples
Let’s say we’re in the http://www.example.com/shop/checkout?order=desc&page=1 action.
current_page?(action: 'process') # => false current_page?(action: 'checkout') # => true current_page?(controller: 'library', action: 'checkout') # => false current_page?(controller: 'shop', action: 'checkout') # => true current_page?(controller: 'shop', action: 'checkout', order: 'asc') # => false current_page?(controller: 'shop', action: 'checkout', order: 'desc', page: '1') # => true current_page?(controller: 'shop', action: 'checkout', order: 'desc', page: '2') # => false current_page?('http://www.example.com/shop/checkout') # => true current_page?('http://www.example.com/shop/checkout', check_parameters: true) # => false current_page?('/shop/checkout') # => true current_page?('http://www.example.com/shop/checkout?order=desc&page=1') # => true
Different actions may share the same URL path but have a different HTTP method. Let’s say we sent a POST to http://www.example.com/products and rendered a validation error.
current_page?(controller: 'product', action: 'index') # => false current_page?(controller: 'product', action: 'create') # => false current_page?(controller: 'product', action: 'create', method: :post) # => true current_page?(controller: 'product', action: 'index', method: [:get, :post]) # => true
We can also pass in the symbol arguments instead of strings.
4Notes
/products/1
==== Code example
current_page?(product_path(@product))
# => true
with resources
/products
==== current_page?(products_path) # => true
current_action? and current_controller?
I use them in link_unless_current_controller helper.
def current_action?(options)
url_string = CGI.escapeHTML(url_for(options))
params = ActionController::Routing::Routes.recognize_path(url_string, :method => :get)
params[:controller] == @controller.controller_name && params[:action] == @controller.action_name
end
def current_controller?(options)
url_string = CGI.escapeHTML(url_for(options))
params = ActionController::Routing::Routes.recognize_path(url_string, :method => :get)
params[:controller] == @controller.controller_name
end
active_link_to helper gem
You should also have a look at https://github.com/twg/active_link_to if you need an 'active' class on your links.