Dynamically display titles with content_for and yield-Ruby on Rails

Introduction

This time, I will introduce __ "How to display titles dynamically using content_for and yield in Rails" __ !!

Some people may have asked "What is dynamic?" (Laughter I was), but it is a concept that appears frequently in programming, but its meaning is __ "The flexibility to change the state and configuration according to the situation and to select according to the situation." __

The implementation content using content_for and yield introduced in this article is mainly the back side of the sentence, "flexibility that can be selected according to the situation".

Let's take a closer look at its flexibility.

Confirmation of deliverables

The following is the implemented product.

_ Top page title _ top.png

Access page title access.png

It's not surprising that a website has multiple pages within the site. For example, the top page that is displayed when you access the home electronics mass retailer site, the access page that introduces how to get to the store, and so on. And the title on each page usually conforms to the page content.

In the implementation of this article, the site name is changed on each page as shown in the above figure. On the top page __ "AAA Electric" (name of home electronics mass retailer) __ On the access page__「Access |AAA Electric "(Page content|Name of home electronics mass retailer)__

Explain the implementation method

First, write the yield statement in the head tag of application.html.erb, which is the common layout of all views.

erb:app/views/layouts/application.html.erb


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

Although it is yield (: title),: title in () can be other code. (: notice,: info, etc.) In the content_for described later, the code in () must be the same as the one described here. (By the way: title is a symbol in ruby ​​notation. The understanding here is not a problem even if it is just a character string.)

The __page_title method __ defined here is defined in app/helpers/application_helper.rb.

app/helpers/application_helper.rb


module ApplicationHelper

  #If no argument is passed, the empty string is the default value.
  def page_title(page_title = '')
    base_title = 'AAA electric'

    #Ternary operator
    page_title.empty? ? base_title : page_title + " | " + base_title
  end
end

An empty string is specified as the default value in the argument of page_title. This will assign an empty string ("") to page_title even if no arguments are passed and it will be used in the operation inside the method.

Then, the __ternary operator __ returns "AAA electric (base_title)" if no argument is passed, and "argument character (page_title) | AAA electric" if an argument is passed.

Although it is a ternary operator, I will not explain it in detail here, but in a nutshell, it is __ "an operator that describes an if statement in one line" __. In other words, the above sentence has the same meaning as the if statement. (When I first saw it, I didn't think it meant the same as if ...)

Conditional expression?true processing:Handling of false

Just in case, the one rewritten with the if statement is described, so if you want to skip the ternary operator, please see here to check the meaning.

# page_title.empty? ? base_title : page_title + " | " + base_Rewrite title with if statement
if page_title.empty?
  base_title
else
  page_title + " | " + base_title
end

The story is a little derailed, but by defining this page_title method, it can be used in application.html.erb.

Then, how is yiield (: title), which is an argument of the page_title method, passed? Yes, it's time for the content_for method.

Moreover, the implementation method is very easy! __ Use the content_for method on each page and just write the common symbol in the first argument and the character string you want to pass in the second argument! __

When implementing like a deliverable

erb:app/views/access/index.html.erb


<% content_for(:title, 'Access' ) %>

This will__The string ‘Access’ is passed to yeild on the common layout page__、page_The argument of the title method becomes'Access', and the title is "Access" like the deliverable.|AAA Electric "(Page content|Name of home electronics mass retailer)".

Conversely, if nothing is entered in the view of the page that is routed as the top page, the title of that page will be "AAA Electric".

Benefits of being dynamic

At the beginning, I explained the meaning of dynamic (flexibility that can be selected according to the situation), but what kind of flexibility is there in this implementation?

For example, let's say AAA Electric changed its name to BBB Electric. Of course, the title must also be changed to the new company name. How should I make changes to the code?

The only answer is __ "change the characters you put in the base_title of the helper method" __.

app/helpers/application_helper.rb


module ApplicationHelper

  def page_title(page_title = '')
    #changes-----------
    base_title = 'BBB Electric'
    # --------------------

    page_title.empty? ? base_title : page_title + " | " + base_title
  end
end

Really only this! This alone will change the title of all other pages that use __content_for from "AAA Electric" to "BBB Electric". __ Maintenance is surprisingly easy.

Conversely, consider an implementation that does not use content_for and yield. The title of each page is statically displayed on each page.

erb:app/views/layouts/application.html.erb


<title>AAA electric</title>

erb:app/views/access/index.html.erb


<title>Access |AAA electric</title>

And let's say the company name has changed, as in the previous example.

Now, how many places do you want to make changes? If you have implemented + | AAA Electric on other pages as well as on the Access page, you will have to modify that number. An implementation that uses __content_for and yield would only need one place. __

This is the power of being dynamic. The flexibility to choose the response that suits your situation.

Finally

The example introduced this time is a very simple implementation method. However, there are many other ways to use content_for and yield, so be sure to give it a try! I will try it too!

We hope that this article will be of some help to you in your learning.

that's all

Recommended Posts

Dynamically display titles with content_for and yield-Ruby on Rails
Implementation policy to dynamically save and display Timezone in Rails
DOM example → Dynamically generate HTML tags and display data on the database
[Ruby on Rails] View test with RSpec
Building Rails 6 and PostgreSQL environment with Docker
Notes on using FCM with Ruby on Rails
[Ruby on Rails] Controller test with RSpec
Rails migration column changes and so on.
[Ruby on Rails] Model test with RSpec
[Ruby on Rails] Add and delete tags and display (success / error) messages using ajax.
[Ruby on Rails] How to display error messages
Introducing Rspec with Ruby on Rails x Docker
Publish the app made with ruby on rails
Display Mat type image on GUI with Swing
Ruby on Rails ~ Basics of MVC and Router ~
Notes on building Rails6 / PostgreSQL with Docker Compose
Rails development environment created with VSCode and devcontainer
[Rails] Procedure for linking databases with Ruby On Rails
How to build API with GraphQL and Rails
Determine the current page with Ruby on Rails
[Ruby on Rails] Upload multiple images with refile
[Ruby on Rails] Ranking display (total, average value)
Easy to display hello world with Rails + Docker
[Ruby on Rails] Individual display of error messages
I made a portfolio with Ruby On Rails
[Ruby On Rails] How to use simple_format to display the entered text with line breaks
[Rails AWS Docker] Build an existing Ruby on Rails + MySQL application with Docker and deploy it on AWS (5)
[Rails AWS Docker] Build an existing Ruby on Rails + MySQL application with Docker and deploy it on AWS (6)
[Rails AWS Docker] Build an existing Ruby on Rails + MySQL application with Docker and deploy it on AWS (3)
[Rails AWS Docker] Build an existing Ruby on Rails + MySQL application with Docker and deploy it on AWS (2)
[Rails AWS Docker] Build an existing Ruby on Rails + MySQL application with Docker and deploy it on AWS (1)
[Rails AWS Docker] Build an existing Ruby on Rails + MySQL application with Docker and deploy it on AWS (4)