- Published on
Dynamic Page Titles with Rails and Slim
- Authors
- Name
- Yair Mark
- @yairmark
When optimising your site for SEO it is very important to use a title for each page so that your user's know where they are. It is also valuable for when the user shares your page.
In a Rails project I am working on, Slim is used for the view templates. We had a generic site title for all pages setup in our application.html.slim
as follows:
doctype html
html lang="en"
head
title My Awesome Site
/...
This is cool if you want the same title for all pages. But customising it per template was a bit more involved.
After a bit of Googling, I came across this question which goes through how to do this for ERB.
As I am new to slim it was not immediately obvious how to port this code to slim. After a bit more Googling I came across this question and this Slim cheatsheet. With all these different sources together I worked out how to implement this in Slim.
First, as per the first linked question we need to update our application_helper.rb
as follows:
module ApplicationHelper
# ...
def title(page_title)
content_for(:title) { page_title }
end
# ...
end
We then need to go into our application.html.slim
and update it as follows:
doctype html
html lang="en"
head
title= content_for?(:title) ? content_for(:title) : "My awesome Site"
/...
Finally, for each view we want a custom title for add the following as the first line or in the appropriate if/conditional block/s:
- title "About Us"
/ ...
For views that you do not want a custom title for or you miss, the default you specified in application.html.slim
will be used.