11

I'm creating a rails app and I must differentiate the header for home page.

I already created a partial with the _home_header version and the _header version to use in every page, but I don't know how can I manage the change.

The header is included in my layout, and I render the same layout for every page. How can I tell to "layout" to use the _home_header version instead of the standard version when I request homepage?

1

4 Answers 4

17

I would use the current_page? helper and look at the root_path.

# app/views/layouts/application.html.erb
<% if current_page?(root_path) %>
    <%= render 'layouts/home_header' %>
<% else %>
    <%= render 'layouts/header' %>
<% end %>
2

Use something like this in application.html.erb

<% if request.original_url == root_url %>  ## Specify the home url instead of root_url(if they are different)
  <%= render 'layouts/home_header' %>      ## Assuming that _home_header.html.erb is under layouts directory
<% else %>
  <%= render 'layouts/header' %>           ## Assuming that _header.html.erb is under layouts directory
<% end %>
1

Typically, you add more specific versions of pages in controller-specific sub directories.

That is, if you have a layout application.html.erb which renders a header partial...

# app/views/layouts/application.html.erb
<!doctype html>
<html>
...
<body>
  <%= render 'header' %>
  ...

This will look for a header partial first in app/views/<controller_name>/ then in app/views/application/. So, your site-wide header would reside in app/views/application/_header.html.erb, and your homepage partial would reside in app/views/home/_header.html.erb, and it would "just work". Rails would load the more "specific" header.

1
  • I know but I must add the default version in every view... i need just to override the header when I load homepage. Commented Mar 25, 2014 at 21:05
1

An option to @meagar suggestion would be use a before_action on your application controller for that:

class ApplicationController
  beore_action :set_header

  private

    def set_header
      @header = if is_my_page
        "Special header"
      else
        "Other header"
      end
    end
end

and in your layouts/application.html.erb:

<title><%=@title%></title>

The bright part of his solution is that all text are kept on the view files, which makes sense. The not-so-bright part is that is harder to follow.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.