Sunday
01Feb2009
Rails 2.3: Localized Views
Sunday, February 1, 2009 at 10:04AM
One of the late-breaking changes to sneak into Rails 2.3 is localized views. If you're staying at all up to date, you know that Rails sports a nifty new internationalization framework as of version 2.2. But in 2.3, if you want to show different views depending on the visitor's locale, it's quite simple.
For example, suppose you have a
But why stop there? Rails doesn't impose any particular limits on the symbols that you can set for
[sourcecode language='ruby']
before_filter :set_expert_mode
def set_expert_mode
I18n.locale = :expert if current_user.expert?
end
[/sourcecode]
And then if you provide, say,
For example, suppose you have a
Pages controller with an about action. Ordinarily, this will render app/views/pages/about.html.erb. But if you set I18n.locale = :es, it will render app/views/pages/about.es.html.erb. If the localized template isn't present, the undecorated version will be used.But why stop there? Rails doesn't impose any particular limits on the symbols that you can set for
I18n.locale, so if you want, you can hijack this system to display different content depending on anything you want. For example, suppose you have some users who are "expert" who should see different pages. Just do something like this:[sourcecode language='ruby']
before_filter :set_expert_mode
def set_expert_mode
I18n.locale = :expert if current_user.expert?
end
[/sourcecode]
And then if you provide, say,
index.expert.html.erb, that version will be displayed to expert users. If there's no special view, they'll just get the normal content.

Reader Comments (1)
This is great!
Do you know if it works with the partial conventions for objects as well? I have a method called #render_with_context that I stick in all my _object.html.erb templates so that my objects can use a different partial depending on whether they are displayed on the home page, in a gallery, as thumbnails etc. I don't really like my implementation and have been trying to come up with something better, and this seems like it might be it.