Set page titles and meta tags in Rails views
When building websites that need to be SEO friendly, we often need to customize the page title and meta tags for individual views.
My preferred way to do this is to
add helper methods
that you can use in the views
to override the defaults.
we might want to be able to
set the page title and meta tags
posts#show view like this:
Now let’s write the helpers
to be able to use such helpers.
First, we’ll write the page title helper.
Add this method to
Now change the title tag
to look something like this:
Now if you set the title in posts#show, you will see the title as “My Post Title | My Awesome Site”, and otherwise it will be “My Awesome Site”.
Next we will set up
the helpers for
the meta tags.
We might need to setup
helpers for description and tags.
We can use a single helper
that can be used like
meta_tag, :description, 'Some description goes here'.
We’ll add two helper methods
to accomplish this.
In the head section of layouts/application.html.erb:
This solution is actually overkill
if we only need to override
description and keywords tags.
Having two helper methods,
similar to the title helper,
would be a much simpler option
in that case.
But if you need the ability
to override many different tags,
the above approach make it simpler.