A Fresh Cup is Mike Gunderloy's software development weblog, covering Ruby on Rails and whatever else I find interesting in the universe of software. I'm a full-time Rails developer and contributor, available for long- or short-term consulting, with solid experience in working as part of a distributed team. If you'd like to hire me, drop me a line. I'm also the author of Rails Rescue Handbook and Rails Freelancing Handbook.

Navigation
« Double Shot #382 | Main | Highlighting Text in Rails »
Sunday
01Feb2009

Rails 2.3: Localized Views

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

February 1, 2009 | Unregistered CommenterLar Van Der Jagt

PostPost a New Comment

Enter your information below to add a new comment.

My response is on my own website »
Author Email (optional):
Author URL (optional):
Post:
 
Some HTML allowed: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong>