jtarr523
jtarr523

Reputation: 361

How would I display different headers in Rails in application.html.erb?

How would I display different versions of headers in Rails in my application.html.erb view? For instance, for my landing page, I have a pretty big header that includes a callout and some sign-up and sign-in buttons. For other static pages, I have a normal small header with a logo and a few links to the right. And for my dashboard when users log in, it will look a little different as well.

How can I display certain headers in an if/else statement where Rails will output the different versions of headers based on the current url or view in my application.html.erb?

Upvotes: 2

Views: 2084

Answers (2)

Vishal S Mujumdar
Vishal S Mujumdar

Reputation: 410

To answer your question with an example this is what you may want to do. Rails has a provision to use nested view templates using the content_for and yield tags. Do the following thing to achieve what you want -

  1. In app/views/layouts/application.html.erb - Add a ternary expression which acts as a if else. While rendering the views rails will look for a <% content_for :custom_header do %> in the view templates. If it doesn't find that it will render the partial app/views/layouts/_default_header.html.erb instead.

    <html>
    <head>
      <title><%= @page_title or "Page Title" %></title>
      <%= stylesheet_link_tag    'application', media: 'all', 'data-turbolinks-track' => true %>
      <%= javascript_include_tag 'application', 'data-turbolinks-track' => true %>
      <%= csrf_meta_tags %>
    </head>
    <body>
      <!-- Code to conditionally load a header -->
      <%= content_for?(:custom_header) ? yield(:custom_header) : render :partial => "layouts/default_header" %></div>
    
      <!-- For the body -->
      <%= yield %>
    </body>
    </html>
    
  2. Now since you say that most pages will have a static small header, save the html code for that in a partial under app/views/layouts/_default_header.html.erb.

  3. In you landing page (for example the the view app/views/welcome/index.html.erb) you can use the content_for tag with the identifier :custom_header that we have used in the application.html.erb Add the following in your landing page.

    <% content_for :custom_header do %>
      <div class="custom-header">
        <!-- Your complex header with sign in and signup links... -->
      </div>
    <% end %>
    

The ternary operator in the application.html.erb will pick up this content from the content_for tag in the landing page and insert the content in place of the yield(:custom_header).

Hope this helps.

Upvotes: 3

Chris Fritz
Chris Fritz

Reputation: 1940

It sounds like you may want to use a nested layout.

Upvotes: 1

Related Questions