Rails, make a different title only on the main page

I am creating a rails application and I have to distinguish the title for the main page.

I have already created a partial version with _home_header and a version of _header for use on each page, but I don’t know how to manage this change.

The title is included in my layout, and I draw the same layout for each page. How can I say β€œlayout” to use the _home_header version instead of the standard version when I request the home page?

+6
source share
4 answers

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

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

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 %> 
+2
source

As an option to the @meagar clause, before_action will be used for your application controller:

 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 layouts/application.html.erb :

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

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

+1
source

Typically, you add more specific versions of pages to sub directories specific to the controller.

That is, if you have a layout application.html.erb that displays a partial header ...

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

This will look for the partial header first in app/views/<controller_name>/ , then in app/views/application/ . Thus, the title of your site will be in app/views/application/_header.html.erb , and part of your home part will be in app/views/home/_header.html.erb , and it will just work. Rails would load a more "specific" header.

0
source

All Articles