Titleizer sets page title to Rails application using I18n.
Add this line to your application's Gemfile:
gem 'titleizer'
And then execute:
$ bundle
Add page titles to your config/locales/*.yml
:
en:
title:
application: My Blog
description: This is my blog.
posts:
index: All posts
show: "%{subject}"
new: New post
edit: Edit post
Modify title tag in app/views/layouts/application.html.erb
:
<!DOCTYPE html>
<html>
<head>
<title><%= title(yield :title) %></title>
:
</head>
You should restart your application after changing locales file. Then you will see the page title as you set.
If you want to set page title using variable, you can set @title_params
in your action:
class PostsController < ApplicationController
def show
@post = Post.find(params[:id])
@title_params = { subject: @post.subject }
end
end
When @post.subject
is "My first post", posts#show
title is as follows:
<!DOCTYPE html>
<html>
<head>
<title>My first post | My Blog</title>
:
</head>
If you want to override page title, you can set preferred title on view file. This feature is useful in some case, such as rendering error page.
For example, if you set view file as follows, the page title become 404 Not Found | My Blog
even if you set title in locales.
<% provide :title, '404 Not Found' %>
- Fork it ( https://github.com/kami30k/titleizer/fork )
- Create your feature branch (git checkout -b my-new-feature)
- Commit your changes (git commit -am 'Add some feature')
- Push to the branch (git push origin my-new-feature)
- Create a new Pull Request