Navigation Highlighting with 2 Pages from the Same Controller - ruby-on-rails

Following a previous post I (almost) successfully implemented highlighted navigation using CSS and Rails.
<ul class="nav">
<li class="<%= "active" if params[:controller] == "sweets" %>"><%= link_to 'Sweets', sweets_path %> </li>
<li class="<%= "active" if params[:controller] == "sweets/new" %>"><%= link_to 'New Sweets', new_sweets_path %> </li>
<li class="<%= "active" if params[:controller] == "tasks" %>"><%= link_to 'Tasks', tasks_path %> </li>'Customers', customers_path %> </li>
<li class="<%= "active" if params[:controller] == "suppliers" %>"><%= link_to 'Suppliers', suppliers_path %> </li>
</ul>
The only issue is that one of my navigational items is for creating a new item rather than being to an entirely different page. I have tried the above using /new on the end of the normal controller text but it hasn't worked.
Is this method possible when navigating to the method pages or do I need to implement it in a different way? Sorry if this is a repeat question but I couldn't find anyone with the same situation.
Thanks in advance and any hints or tips are always welcome.

You can check for action as well:
if params[:action] == 'some_action'

Related

Ruby use conditional operator to check current path

I'm trying to create a navbar that highlights the li item on which page I am.
In my code below I'm trying to use a conditional operator to see if the current path is correct. Or at least that's what I think i'm doing.
<li id="home-link" data-hook class="<%= root_path ? "active" : "" %>"><%= link_to Spree.t(:Home), spree.root_path %></li>
<% if spree_current_user %>
<li id="home-link" data-hook class="<%= products_path ? "active" : "" %>" ><%= link_to Spree.t(:products), spree.products_path %></li>
<% end %>
What I then expect to happen is that if i'm on the home page the li get's the class active,
what currently happens is that all li items get the class active.
How can I check the current path?
No, you are testing if the path helpers are true, and they are as they return a String. That's why active is always set.
Take a look at current_page?:
<% product_active = 'active' if current_page?(controller: 'products', action: 'index') %>
<li id="home-link" data-hook class="<%= product_active %>">
EDIT: As #NensiMakawana suggets, you can alternatively use the active_link_to gem.

Dynamically add active class to bootstrap li in Rails

in the bootstrap navigation bar. You can get the effect of a button being clicked by adding the class active . Naturally, I want to use this on my pages. For example if I'm on the about us page I want the about us button clicked.
What is the best way to go about this? I was going to go to each page and at the bottom have a jQuery function add the class active to it. Is there a better way?
Read about current_page? here
You can add a method for handle logic with current_page?, example a method :
module ApplicationHelper
def active_class(link_path)
current_page?(link_path) ? "active" : ""
end
end
example bootstrap navbar template
<div class="navbar">
<div class="navbar-inner">
<a class="brand" href="#">Title</a>
<ul class="nav">
<li class="active">Home</li>
<li>Link</li>
<li>Link</li>
</ul>
</div>
</div>
So, on view looks like
HTML
<li class="<%= active_class(some_path) %>">
<%= link_to "text of link", some_path %>
</li>
HAML
%li{:class => active_class(some_path)}
= link_to "text of link", some_path
Or you can use request.fullpath to get current full of path if a current path have a parameter
example
<ul>
<% Contry.all.each do |c| %>
<li class="snavitem <%= active_class(contry_path(c)) %>">
<%= link_to "show #{c.name}", contry_path(c) %>
</li>
<% end %>
</ul>
and on your application_helper.rb
def active_class(link_path)
request.fullpath == link_path ? "active" : ""
end
read about request.fullpath here
in my opinion, a cleaner way to achieve that is to write a link_to_in_li method in application_helper.rb:
def link_to_in_li(body, url, html_options = {})
active = "active" if current_page?(url)
content_tag :li, class: active do
link_to body, url, html_options
end
end
then use it this way
<%= link_to_in_li "Home", root_path, id: "home_link" %>
I find the code inside li a little difficult to read.
For anyone having trouble making sense of this, here is an example with my paths and filenames laid out explicitly. As a pretty new person to rails, I was having trouble figuring it out. Thanks to the other people who answered above, as it helped me figure it out!
I placed the Bootstrap navbar in my application.html.erb file:
<div class="navbar-header">
<a class="navbar-brand" href="/">Mapper</a>
<ul class="nav navbar-nav">
<li class="<%= is_active?('/') %>"><%= link_to "Home", '/' %></li>
<li class="<%= is_active?('/main/map') %>"><%= link_to "Map", '/main/map' %></li>
<li class="<%= is_active?('/main/about') %>"><%= link_to "About", '/main/about' %></li>
</ul>
</div>
This goes in the application_helper.rb file:
module ApplicationHelper
def is_active?(link_path)
current_page?(link_path) ? "active" : ""
end
end
That's it! Now your application will dynamically add the 'active' class to whatever page is currently being viewed (i.e. it's corresponding list item in the navbar). This is much simpler (and more DRY) than adding the navbar manually to each page (view) and then updating the 'active' class.
I'll post my answer that I created based on these others because in case of CRUD views the active class wasn't been placed.
module ApplicationHelper
def active_class(name)
controller_name.eql?(name) || current_page?(name) ? 'active' : ''
end
end
My views use something like this:
<ul class="nav navbar-nav">
<li class="nav-item <%= active_class('/') %>">
<a class="nav-link" href="/">Home</a>
</li>
<li class="nav-item <%= active_class('leads') %>">
<a class="nav-link" href="/leads">Leads</a>
</li>
</ul>
<ul class="nav navbar-nav pull-right <%= active_class(edit_user_registration_path) %>">
<li class="nav-item ">
<a class="nav-link" href="/users/edit">Perfil</a>
</li>
<li class="nav-item">
<%= link_to('Sair', destroy_user_session_path, method: :delete) %>
</li>
</ul>
Please try this in each page, check the cotroller or action and add the css
For example:
<li class= <%= (controller.controller_name.eql?('pages') && controller.action_name.eql?('index') )? 'active':''%> ><%= link_to 'my page', pages_path%></li>
You may define a helper method in application_helper.rb
def create_link(text, path)
class_name = current_page?(path) ? 'active' : ''
content_tag(:li, class: class_name) do
link_to text, path
end
end
Now you can use like:
create_link 'xyz', any_path which would render as <li class="active">xyz</li>
Perfect for bootstrap navigation!
Why limit yourself to only li elements? And why not support multiple class names along with active? This solution lets me:
Support not only plain text but HTML inside link_to (e.g. add an icon inside the link)
Add just few lines of code to application_helper.rb
Append active to the whole class name of the link element instead of it being the sole class.
So, add this to application_helper.rb:
def active_class?(class_name = nil, path)
class_name ||= ""
class_name += " active" if current_page?(path)
class_name.strip!
return class_name
end
And on your template you can have something like this:
<div class="col-xs-3">
<%= link_to root_path, :class => active_class?("btn btn-outline-primary", root_path) do %>
<i class="fa fa-list-alt fa-fw"></i>
<% end %>
</div>
You can also specify or not a class_name and use it like this:
<li class="<%= active_class?(root_path) %>">Home</li>
Thanks to previous answers 1, 2 and resources.

Twitter Bootstrap Pills with Rails 3.2.2

I followed the basic railscast for using Twitter Bootstrap in Rails application. Everything was great, until I had to push to heroku, then I had some problems with pg gem, and I had to rake assets:precompile to push it ok. Finally I solved.
Now, I'm trying to use pills in my application, I have copy/paste from documentation and changed the url in href :)
<div class="container">
<div class="row">
<div class="span3">
<p> Lorem Ipsum</p>
</div>
<div class="span9">
<ul class="nav nav-pills">
<li class="active">Home</li>
<li>Products</li>
<li>Categories</li>
</ul>
</div>
</div>
</div>
When I push one of the links, I'm redirected to the right url but the selected option doesn't change to class="active". I don't know why... I thought it was the javascript but hover property works ok... I mean, when the mouse is over an option (diferent from active) its style changes ok.
I tried rake assets:clean, but no change is made
Thanks
You actually have to handle this by yourself!
Your list should look something like
<li class="<%= 'active' if params[:controller] == 'yourdefaultcontroller' %>">Home</li>
<li class="<%= 'active' if params[:controller] == 'products' %>">Products</li>
<li class="<%= 'active' if params[:controller] == 'categories' %>">Categories</li>
You need to specify in each request which tab is the active one. You can do this by relying on the name of the controller (and action if need be) that is passed in the params hash.
You can use something like this:
<li class="<%= 'active' if current_page?(root_path) %>"><%= link_to "Home", root_path %></li>
<li class="<%= 'active' if current_page?(about_path) %>"><%= link_to "About", about_path %></li>
<li class="<%= 'active' if current_page?(contact_path) %>"><%= link_to "Contact", contact_path %></li>
I used a helper to implement this in the style of Rails' form helpers.
In a helper (e.g. app/helpers/ApplicationHelper.rb):
def nav_bar
content_tag(:ul, class: "nav navbar-nav") do
yield
end
end
def nav_link(text, path)
options = current_page?(path) ? { class: "active" } : {}
content_tag(:li, options) do
link_to text, path
end
end
Then, in a view (e.g. app/views/layouts/application.html.erb):
<%= nav_bar do %>
<%= nav_link 'Home', root_path %>
<%= nav_link 'Posts', posts_path %>
<%= nav_link 'Users', users_path %>
<% end %>
This example produces (when on the 'users' page):
<ul class="nav navbar-nav">
<li>Home</li>
<li>Posts</li>
<li class="active">Users</li>
</ul>

How can i conditionally style a <li> in rails?

I have a rails app using a ul as a toolbar. I want to have a style (selected) to apply to the page the user is on.
How can I do that?
This is what I have so far, but the selected style is hard coded and I'm also not sure how to know what page is selected.
<ul>
<li class="firstItem"><%= link_to "About", '/about' %></li>
<li class="item"><%= link_to "Page1", '/page1' %></li>
<li class="item selected" <%= link_to "Page2", '/page2' %></li>
<li class="item"><%= link_to "Contact", '/contact' %></li>
<li class="lastItem"><%= link_to "Blog", '/blog' %></li>
</ul>
I agree totally with Jarrod's advice, but just in case you encounter the need to process additional conditions (and want to avoid ugly embedded ruby in your HTML code), take a look at Rails' content_tag method.
With it, you can replace something like:
<li class=<%= #post.active? ? 'active' : 'suspended' %>>
<%= link_to #post.name, post_path(#post) %>
</li>
With something like:
<%= content_tag :li, link_to(#post.name, post_path(#post), :class => #post.active? ? 'active' : 'suspended' %>
And of course, sticking this code into a helper and calling it from there will earn you more elegance-points.
Hope this helps.
PS: This is my first post on Stackoverflow, please be gentle. :)
if each li is linked to different controller you can use controller_name to add or not the selected class
Here is an example from my app, it's in haml
%ul
%li
%a{:href => '/kebabs', :class => ('current' if controller_name == 'kebabs')} Admin kebabs
%li
%a{:href => '/statistics', :class => ('current' if controller_name == 'statistics')} Statistiques
%li
%a{:href => '/people', :class => ('current' if controller_name == 'people')} Admin Personnes
cheers
You can also use css for this. Give each the body each page a class and id from your controller and action names.
<body class="<%= controller.controller_name %>" id="<%= controller.action_name %>">
Then give your ul and li elements an id.
<ul id="nav'>
<li id="about"></li>
<li id="contact"></li>
<li id="blog"></li>
</ul>
Now you can reference a specific link on a specific page from your stylesheet.
body.blog#index ul#nav a#blog:link
So if you want to make section links 'sticky' you can reference them all at once, leaving out the body id.
body.blog ul#nav a#blog:link,
body.contact ul#nav a#contact:link {
background-color: red;
}
Check out more on CSS selectors.

Changing Current Tab in Rails

I have a list of tabs at the top of my application that I include in a general layout in application.html.erb. They look like this:
<li class="current"><%= link_to "Home", provider_path(current_user.id), :method=> "GET"%> </li>
<li><%= link_to "Edit Profile", edit_student_path(current_user.id) %> </li>
<li><%= link_to "Search", provider_search_path %> </li>
I want to change the selected tab to the "current" one, when I hit that page. So when I click Edit Profile and the Edit Profile page loads, the tabs should appear as follows:
<li><%= link_to "Home", provider_path(current_user.id), :method=> "GET"%> </li>
<li class="current"><%= link_to "Edit Profile", edit_student_path(current_user.id) %> </li>
<li><%= link_to "Search", provider_search_path %> </li>
Is there a way to do this outside of adding javascript to the page which is displayed? Or if there is what is generally best practice for doing this in the DRYest way possible.
Thanks
You can use controller.class == and controller.action_name == to figure out exactly which controller and action you are on
so it would be something like
<li class="<%= controller.class == ProviderController and controller.action_name == 'show' ? 'current' : '' %>"><%= link_to "Home", provider_path(current_user.id), :method=> "GET"%> </li>
<li class="<%= controller.class == StudentController and controller.action_name == 'edit' ? 'current' : '' %>"><%= link_to "Edit Profile", edit_student_path(current_user.id) %> </li>
<li class="<%= controller.class == ProviderController and controller.action_name == 'search' ? 'current' : '' %>"><%= link_to "Search", provider_search_path %> </li>
I believe there are some ways to get the current url for the page you are on, but then your "active" styling will be dependent on only getting to that action via that path, which may not always be the case depending on the routes, this way will ensure the view shows what is true based on what was actually run, not what the url is in the address bar
You could try something like:
<li class="<%= controller.controller_path == 'provider' ? 'current' : '' %>"><%= link_to "Home", provider_path(current_user.id), :method=> "GET"%> </li>
<li class="<%= controller.controller_path == 'student' ? 'current' : '' %>"><%= link_to "Edit Profile", edit_student_path(current_user.id) %> </li>
<li class="<%= controller.controller_path == 'search' ? 'current' : '' %>"><%= link_to "Search", provider_search_path %> </li>
...and just check which controller you're coming from.
Take a look at TabsOnRails
You could just do this:
<%= current_page?(:controller => 'your_controller', :action => 'index') ? 'current' : '' %>
I made a helper for this that can accept any number of arguments which is useful for nested resources, but it also accepts a single controller name just like the other answers.
application-helper.rb:
def is_active(*links)
links.each { |link| return "active" if params[:controller] == link }
end
application.html.erb:
<li class="<%=is_active('home')%>">...</li>
Or
Example usage with HAML & nested resource(will be active for any of the provided controller names):
applcation.html.haml:
%li{:class => is_active('blogs', 'comments')}
When you switch pages you could pass something like #current_tab back to the erb from the controller methods. Then use #current_tab to decide which li should be the current class. Alternatively, you could give each li and id or some unique attribute and simply change the class with your JavaScript framework of choice.
I'm so not claiming this is the best way to do this, however I am brave enough to post what I came up with :)
Some example menu links from my layout:
<li class="nav-calendar"><%= menu_link_to 'teachers', 'show_date', 'Calendar', calendar_url %></li>
<li class="nav-announcements"><%= menu_link_to 'announcements', nil, 'Announcements', announcements_path %></li>
Then I created this helper:
def menu_link_to(*args, &block)
controller = args.shift
action = args.shift
if controller == controller_name && (action.nil? || action == action_name)
if args.third.nil?
args.push({:class => 'selected'})
else
args.third.merge!({:class => 'selected'})
end
end
link_to *args, &block
end
I did this in the application helper and it seems to work fine:
def current_page(path)
"active" if current_page?(path)
end
Then call like this:
<li class="<%= current_page(root_path)%>"> <%= link_to "Home", root_path %></li>

Resources