2

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!

4 Answers 4

7

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" %>'>
Sign up to request clarification or add additional context in comments.

Comments

3

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')

Comments

1

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 %> 

Comments

0

Try this in ur view , it will works

<% if (controller_name == 'applications' && action_name == 'index') %>
    <div class="header">
<%else%>
    <div class="header-2">
<%end%>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.