Custom Meta Titles in Rails: A quick guide

railsdesigner

Rails Designer

Posted on March 19, 2024

Custom Meta Titles in Rails: A quick guide

This article was previously published on Rails Designer.


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, 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.

So, let's add a few lines so every page has its own page title. And make your users a bit happier using your app.

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" %>
Enter fullscreen mode Exit fullscreen mode

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 check 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" %>
Enter fullscreen mode Exit fullscreen mode

Where Dashboard could be any value that makes sense for the page.

And that's all you need to do to add meta title to your Rails apps. An easy change, but one that makes a big difference to the users of your Rails app.

💖 💪 🙅 🚩
railsdesigner
Rails Designer

Posted on March 19, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related