I have a syntax issue I'm trying to sort out. I'm just trying to check if a controller/action is loaded, and if so do something, and if not do something else, seems simple. This gives me an error:
<% if (:controller => 'home', :action => 'index') do %>
<div class="header">
<% else %>
<div class="header-2">
<% end %>
Can someone assist me with the syntax issue here? Thank you!
You have to modify the if clause like this:
<% if controller_name == 'home' && action_name == 'index' %>
Additionally, if have to call this more than once, I'd suggest you define a helper.
application_helper.rb
def home_index?
controller_name == 'home' && action_name == 'index'
end
This way your code will be a lot more readable:
some_view.html.erb
<div class='<%= home_index? ? "foo" : "bar" %>'>
You can use a Rails provided helper to check those kind of things (current controller/action, parameters, ...): current_page?
<% if current_page?(controller: 'home', action: 'index') %>
<div class="header">
<% else %>
<div class="header-2">
<% end %>
Documentation: http://api.rubyonrails.org/classes/ActionView/Helpers/UrlHelper.html#method-i-current_page-3F
Using this helper you can also check for specific parameters:
current_page?(controller: 'home', action: 'index', page: '2')
In the view, you'll need to check for controller_name
and action_name
. Try this
<% if controller_name == 'home' && action_name == 'index' %>
<div class="header">
<% else %>
<div class="header-2">
<% end %>
Try this in ur view , it will works
<% if (controller_name == 'applications' && action_name == 'index') %>
<div class="header">
<%else%>
<div class="header-2">
<%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.