Current page class in rails app - html

I have simple navigation bar in my rails app(Home, News, Contact, etc). And I need to define current page to add :class => 'active'. I find few solution to define current page. And I even created own version. But all of them are reduced to one:
<li class=<%= current_page?(tratata) ? "active" : nil %>...</li>
How I can to apply this solution to all <li> - elements but not to write this every time?

One way to do this is to check if the page the user is on matches the name of the controller they're visiting (you could also do a controller name / action name combination for extra specificity).
application_helper
def nav_helper(arg)
controller_name == arg ? "current" : ""
end
view
<li class="<%= nav_helper('about') %>">
A link
</li>
EDIT:
Woops, I wrote this before you edited your question. To add this to all 'li' tags, use another helper which uses content_tag and place the nav_helper method inside of it.

This is not the best way to do it, but will give you some thoughts on pulling the current controller and action.
You can look at https://github.com/weppos/tabs_on_rails for more ideas on how to make it cleaner code. But this requires a bit more setup. You would create a tabs_tag function that would check the current page and do different styling. Personally, I didn't care for this gem too much and prefer to style my pages my own way.
<%= tabs_tag do |tab| %>
<%= tab.home 'Homepage', root_path %>
<%= tab.dashboard 'Dashboard', dashboard_path %>
<%= tab.account 'Account', account_path %>
<% end %>
if "#{controller.controller_name.to_s}.#{controller.action_name.to_s}" == "pages.index"
<li class='active'>
else
<li>
end
or use a helper method
def current_page(page,action)
if controller.controller_name.to_s == page && controller.action_name.to_s == action
'active'
else
'not_active'
end
end
and in your view
<li class="<%= current_page('pages','index') %>">

Related

Change a li tag class depending on the page the user is in

I have a menu and I want to put bold in the menu li depending the page I'm in.
I'm currently doing it like this
<li><%= link_to 'Home', users_path, class: "#{'font-bold' if current_page?('/users')}" %></li>
<li><%= link_to 'Profile', profile_path(current_user), class: "#{'font-bold' if !current_page?('/users') && (current_page?(controller: 'profiles', action: 'show') || current_page?(controller: 'profiles', action: 'edit'))}" %></li>
but for example if I go to /users/new it throws an error
No route matches {:action=>"show", :controller=>"profiles"}
I guess I could continue adding conditions but this feels like a terrible way to do this.
Whats the best way to do this?
So the error you see occurs because it seems like your missing a profiles_controller or the show action inside of it.
For your question:
I would only play around a bit with the conditions, to shorten your if statement, or you could try to use a view helper.

Ruby on Rails simple dropdown does not retain value on a page refresh using cookies

I have this very simple dropdown that selects the currency I want my page to display in. However, whenever I change the currency and then refresh the page, the selected option changes back to USD (the default value). I attempted to use cookies, but it is not working.
Here is my HTML which is just a form that calls a method in my controller:
<%= form_tag "/cryptos/currency_selector" do %>
<%= select_tag(cookies[:currency_symbol], options_for_select([['USD'], ['JPY'], ['AUD'], ['EUR'], ['GBP'], ['CHF']], params[:currency_symbol]), :onchange => "this.form.submit();") %>
<% end %>
Controller Code which just prints out cookie value for testing:
#handles currency conversion dropdown selector
def currency_selector
puts cookies[:currency_symbol]
end
It's not even setting my cookie since I get an empty string in the terminal. Any help would be greatly appreciated!
First the form on your page:
<%= form_tag "/cryptos/currency_selector" do %>
<%= select_tag(:currency_symbol,
options_for_select(
['USD', 'JPY', 'AUD', 'EUR', 'GBP', 'CHF'], cookies[:selected_currency]
),
onchange: "this.form.submit();") %>
<% end %>
And in your controller method to which /cryptos/currency_selector points to:
def currency_selector
cookies[:selected_currency] = params[:currency_symbol]
redirect_back fallback_location: root_url
end
Further improvements you might consider:
Move the list of available currencies into a model or at least a constant.
Give the /cryptos/currency_selector path a proper name in your routes.rb and use that name in your form instead of the hardcoded path.

how to highlight current link in rails 3

I am trying to highlight curent link. I used this question for ideas here
I have simple menu, that is based on this structure:
<li>
<%= #waste_root.name %>
<ul>
<% #wast_child_ids.each do |it| %>
<li><%= link_to it.name, products_path(:category => it.name), class: "#{cp(products_path)} additional_class" %>
</li>
<%end%>
</ul>
</li>
In Aplication helper:
def cp(path)
"current" if current_page?(path)
end
In CSS file:
.current {
color:red;
}
What I get is all links are in red color. I don't get it. For others it worked just fine.
I think your path in view should look like this:
<li>
<%= #waste_root.name %>
<ul>
<% #wast_child_ids.each do |it| %>
<li><%= link_to it.name, products_path(:category => it.name), class: "#{cp(products_path(:category => it.name))} additional_class" %>
</li>
<%end%>
</ul>
</li>
Because, you're passing a param category in products_path and hence current_page? isn't able to judge the correct relative path. Also, it'd be better if you use the _url(complete path) instead of relative path. It'll be much clear to cross check and to understand as well.
You need to pass the category.
<%= link_to it.name, products_path(:category => it.name), class: "#{cp(products_path(:category => it.name))} additional_class" %>
They're all on the products path because you're just differentiating based on parameters. So just passing the products path they all return true, you need to differentiate based on the parameters by passing them too as you've done in your link

regarding using render in ruby on rails

I am new to rails and still working on fundamentals, so any tips and advice are greatly appreciated!
I've made a functional contact page on a website, and I would like to be able to render the form and functionality of inside a tab on a different page. I have the following code in the static_pages folder in my views folder:
<div id="tabs">
<ul>
<li>About</li>
<li>Contact</li>
</ul>
<div id="tabs-1">
<%= render "shared/about"%>
</div>
<div id="tabs-5">
<%= render "contact/new"%>
</div>
where <%= render "contact/new"%> corresponds to the new.html.erb file in contact in views.
the relevant code inside my routes.rb is
match 'contact' => 'contact#new', :as => 'contact', :via => :get
match 'contact' => 'contact#create', :as => 'contact', :via => :post
and here is my controller:
class ContactController < ApplicationController
def new
#message = Message.new
end
def create
#message = Message.new(params[:message])
if #message.valid?
NotificationsMailer.contact_pr(#message).deliver
redirect_to(root_path, :notice => "Message was successfully sent.")
else
flash.now.alert = "Please fill all fields."
render :new
end
end
end
However, It seems that whatever I try I still am unable to render the form. I apologize if this is a very simple question, and I am mostly interested in getting better at fundamentals in Ruby on Rails so any advice is appreciated! Thanks!
If you want to render this form in other templates (and you do), you should extract it to partial named for example: _form.html.erb.
Then, you should put
<%= render 'contact/form' %>
everywhere you need this partial in view (including new.html.erb template).
When you are done with this, you should leave
render :new
in controller, as it works a little bit different than in view and it renders appropriate action template instead of partial.
Of course, you need to set #message variable everywhere you need this partial. Or, you can put in your partial:
<%= form_for(#message || Message.new) do |f| %>
More info about layouts and rendering here.

How can I populate a div with Rails code when a link is clicked?

I'm trying to populate some li tags with this code:
<% #events.each do |event| %>
<li>
<span class="eventname"><%= event.name %></span>
<span class="eventlocation"><%= event.location %></span>
</li>
<% end %>
And I have some links that say "today", "tomorrow" etc and when I hit today I want the events from today to show up. If I hit tomorrow I want tomorrow's to show up. I've looked everywhere through AJAX tutorials and javascript tutorials and I'm completely lost on how to do this in rails.
One way I considered doing is having this block of code be a partial, and change it slightly for each partial so that the specific events that I want to show come up. But then I'm still stuck with the same problem, I'm not sure how to show a specific partial based on the click of a link.
We will have one partial that would render a set of given events (any type) let's call it _events.html.erb
_events.html.erb:
<% events.each do |event| %>
<li>
<span class="eventname"><%= event.name %></span>
<span class="eventlocation"><%= event.location %></span>
</li>
<% end %>
Then we would create an action named fetch_events that returns a js response.
Class EventsController < ApplicationController
def fetch_events
#events = Event.where(type: params[:type])
respond_to do |format|
format.js
end
end
end
ofcourse in routes.rb
match 'fetch_events/:type' => 'events#fetch_events', as: :fetch_events
now we build out fetch_events.js.erb, this file will set the contents of the div with id 'events' to the rendered partial.
fetch_events.js.erb:
$('#events').html(<%= escape_javascript(render :events, events: #events) %>)
Now in your page view add a have div with id 'events' that will contain the response, while
the ajax could be called using link_to
<%= link_to 'today', fetch_events_path(type: :today), :remote => true %>
<%= link_to 'tomorrow', fetch_events_path(type: :tomorrow), :remote => true %>