[Ruby] [Rails] How to change the page title of the browser for each page

less than 1 minute read

Target

スクリーンショット 2020-06-27 10.43.42.png

Development environment

・ Ruby: 2.5.7
Rails: 5.2.4
・ Vagrant: 2.2.7
-VirtualBox: 6.1
・ OS: macOS Catalina

Premise

The following has been implemented.

Slim introduction

Implementation

1. Edit ʻapplication_helper.rb`

application_helper.rb


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

[Explanation]

** ◎ Set the base title (app name, etc.) and assign it to a variable. ** **

base_title = "Bookers"

** ◎ If the title of each page received as an argument is empty, only the base title is displayed. ** **

if page_title.empty?
  base_title

** ◎ If the title of each page received as an argument exists, both titles are displayed. ** **

else
  "#{ page_title } | #{ base_title }"

If page_title is” book list “, it will be displayed as book list | Bookers.

2. Edit the view

① Edit ʻapplication.html.slim`.

slim:application.html.slim


/Change before
title
  | Bookers

/After change
title
  = full_title(yield(:title))

② Edit the view of each page.

As an example, set the title of books / index.html.slim.

slim:books/index.html.slim


/Postscript
= provide(:title, 'Book list')