Skip to main content

Rails I18n and 404/500 Error Pages

Blog post   •   Jan 13, 2010 12:34 GMT

If you have a multilingual site it makes sense for your 404 and 500 error pages to be multilingual as well. Rails supports multilinguality by serving up error pages with a path like public/500.sv.html, where sv is the locale. In the case where Rails itself is fundamentally broken or fails to respond your webserver will respond with public/500.html, so we need that file as well. A way to achieve this is to keep your 404 and 500 pages as ERB templates with I18n.translate lookups under app/views/errors and have a Rake task that generates the static files under public:

Gist

That Rake task can then be invoked by Capistrano in an after_update_code deploy hook to make the pages available in production.

Comments (8)

    This is what I did:

    http://pastie.org/783449

    ...enabled with:

    class ApplicationController < ActionController::Base
    inlcude Application::ErrorFilters
    end

    I guess my solution won't work for non-Rails-triggered 500 errors (haven't tested) when page-caching is not used, but haven't tested that yet.

    - grimen - Jan 18, 2010 18:43 GMT

    Is this solution suppose to render any layout as well?  Another question, which is the purpose of the with_locale method?

    Thanks for sharing.

    - bolsanova - Jun 09, 2011 19:35 GMT

     Is thi

    - bolsanova - Jun 09, 2011 19:36 GMT

    Is this solution suppose to render any layout as well?  Another question, which is the purpose of the with_locale method?Thanks for sharing.

    - Unknown - Jun 10, 2011 05:29 GMT

    Hi,
    The rake task doesn't use Rails' render method, and doesn't render layouts. It just interprets the ERB files you provide in app/views/errors/.

    The I18n.with_locale method lets you run a block without changing your I18n.locale. It temporarily sets the locale, runs the block, and resets the locale. I use it often at the Rails console, to quickly look at the result of some code under different locales. Or to set translated attributes in AR: 
    I18n.with_locale(:en) { Category.find(1).update_attribute :name, "Name in English" }
    I18n.with_locale(:sv) { Category.find(1).update_attribute :name, "Namn på svenska" }

    Very useful.

    - Martin Svalin - Jun 10, 2011 05:41 GMT

    Thank you for your quick answer :)

    - Unknown - Jun 10, 2011 05:51 GMT

    Hi!

    Thanks for such a knowledgeable post.

    <a href="http://airul.id">Airul</a>

    - Market Research Vietnam - Apr 26, 2016 13:58 GMT

    Hi!

    Thanks for such a knowledgeable post.

    - Kopi Hijau - Jun 09, 2016 03:57 GMT

Add comment

Comment