I figured I should blog the title helpers I made of late.
First, example usage. In an erb view:
gives a title like “Foo – My Site”.
gives the title “Foo”.
gives the title “Welcome to My Site!”.
Things look even nicer in Haml:
Displaying the title
I like to define an
ApplicationLayoutHelper for helpers that will only be used in that layout (you’ll need to declare
helper :all or
helper ApplicationLayoutHelper in your
ApplicationController). If you want to, though, you can just stick this helper method in
1 2 3
SITE_TITLE is e.g. “My Site” from the examples above. Instead of a constant, you might want to use an environment variable or a configuration object – whatever.
Note that we apply
h() in this helper, so don’t apply it to the title again or things can become overescaped.
Now, just use this helper where you want to display the title – typically in your application layout:
Setting the title
I like to be able to set the title from controller as well as from its views. Thus, the setters are defined in
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
instance_variable_set bits are necessary when you set the title from a view: in Rails, controllers and views only share instance variables because Rails copies them to the view behind the scenes. If we set an instance variable on the controller after that has happened, we must copy it over ourselves.
Bonus tip: you can override these setters per-controller if you want to:
1 2 3 4 5 6
This isn’t rocket surgery, but I thought it was worth blogging. I like the
self.title= syntax a lot.