Meta titles are one of those stone age tools browsers have had for ages. It was introduced in HTML 2.0, around 1995 (and supported by Mosaic, Netscape Navigator and Internet Explorer—good times!). It is still used, today, by web browsers to label the window or tab in which the web page is displayed. This helps users to identify and switch between pages they have open.
This is commonly the only (visible/user-focused) meta tag I add to my Rails apps. I might also add a meta-description for some public-facing pages, like the log in and sign up pages. This is all assuming the Rails app is only accessible through authentication.
When you create a new Rails app, the title is set to the application’s name you gave it. This means, for an app named Rails Designer, every title would be Rails Designer too. This is hardly useful for your users.
I recently added category-specific meta titles to the Rails Designer Library. As this process is similar for Rails apps, I wanted to document it for others to learn from. So, let’s add a few lines so every page has its own page title.
Add a custom title-tag to your Rails app
First, find the the <title>
tag in your Rails app, typically it’s in app/views/layouts/application.html.erb
, but maybe you extracted the code into its own partial, eg. app/views/shared/_head.html.erb
.
Replace the name with the following:
<%= content_for?(:page_title)? "#{yield(:page_title)} - Rails Designer" : "Rails Designer" %>
Rails’ content_for
is a helper method that allows you to insert content into a specific placeholder in your layout, enabling dynamic content rendering within your application’s views. In above code, it checks if page_title
value is present. If it is set, yield
it and append - Rails Designer
. If it is not set, just display Rails Designer
.
If you refresh the page, all pages’ titles now should display Rails Designer
. If that was the name you have your Rails app, not much has changed.
So now let’s change that. For every page you want to display a unique, open it and add the following (preferably at the top):
<% content_for :page_title, "Dashboard" %>
Where Dashboard
could be any value that makes sense for the page.
And that’s all you need to do to add meta titles to your Rails apps. An easy change, but one that makes a big difference to the users of your Rails app.