Reputation: 2494
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?
Upvotes: 11
Views: 5725
Reputation: 2602
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 %>
Upvotes: 17
Reputation: 53018
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 %>
Upvotes: 2
Reputation: 20116
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.
Upvotes: 1
Reputation: 239250
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.
Upvotes: 1