Kevin Dark
Kevin Dark

Reputation: 2149

How to use a post title as the page title for the browser in Rails 4

I can't seem to figure out how to turn a Post title on the blog app I am building into the page title. Below is the helper I am using and the line of code in the application layout. I would like to know what I need to do in order to have each post title also be the page title. Thank you in advance for any help you can provide.

Application helper

 module ApplicationHelper
   def full_title(page_title)
     base_title = "Business Name"
     if page_title.empty?
       base_title
     else
       "#{base_title} | #{page_title}"
     end
   end
 end

Application Layout

<title><%= full_title(yield(:title)) %></title>

show.html.erb

<h1><%= @post.title %></h1>
  <p>
    <%= @post.body.html_safe %>
  </p>
<%= link_to 'Back to Posts', posts_path %>

Upvotes: 0

Views: 67

Answers (3)

jbmyid
jbmyid

Reputation: 2015

in your posts/show.html.erb view

<% content_for :title, @post.title %>

Upvotes: 1

Siva
Siva

Reputation: 8058

In your application.html.erb

<head>
  <%= yield :title %>
</head>

In your view

<% content_for :title do %>
  <title><%=full_title(@post.title)%></title>
<% end %>

Upvotes: 0

Pavan
Pavan

Reputation: 33552

As commented By @jbmyid,use content_for like this

def full_title(page_title)
  base_title = "Business Name"
  if page_title.empty?
  content_for :title, base_title.to_s
  else
  "#{base_title} | #{page_title}"
end

use it in your application layout as like:

<title><%= yield(:title) %></title>

then call it in your templates:

<% full_title(@post.title %>

Upvotes: 0

Related Questions