I got tired of @page_title variables being sprinkled around in controllers and views on Speaker Deck, so I made good use of Rails’ I18n API to define them all in one spot.
My config/locales/en.yml now looks something like this:
To make this work, add a #page_title helper method, which looks up the page title translation using the controller and action name.
The helper also passes all of the instance variables assigned in the controller, so you can use any of those variables in your page title. The only caveat is that we have to define #to_s in order for our model objects to show up properly in the title:
Now in our layout, we can use our new helper:
I’m really happy with how this little hack worked out. This almost seems like something that should be in Rails core. Maybe I’ll have to submit a pull request…
I am Brandon Keepers, and I work at GitHub on making Open Source more approachable, effective, and ubiquitous. I tend to think like an engineer, work like an artist, dream like an astronaut, love like a human, and sleep like a baby.