Rails 4 i18n, how to translate routes where subdomain is used for the locale

后端 未结 3 1528
自闭症患者
自闭症患者 2021-02-09 16:27

I am using subdomains to determine the locale in a Rails 4 website. I have this working with a locale switcher exactly the way I want it but now I need to translate the routes a

3条回答
  •  暗喜
    暗喜 (楼主)
    2021-02-09 16:56

    EDIT:

    This gem is my recommended way to do it. Supports multiple languages without reloading the routes (Which my example didn't). You have to change very few things but it's more consistent than the code below. route translator

    Original answer (not working):

    This is what have worked for me, you can try it out, in your routes for example you can put:

    AppName::Application.routes.draw do
        get "/#{I18n.t("index")}", :to => "pages#index", :as => "index"
        get "/#{I18n.t("contact")}", :to => "pages#contact", :as => "contact"
    end
    

    this will get you the routes in your default locale when you run the app, however in runtime, when you change your locale you need to redraw your routes in order to get the routes for the new locale.

    I18n.locale = :es #different locale
    AppName::Application.reload_routes!
    

    Assuming your default_locale is :en, this example will take the first routes from:

    en:
      index: "index-in-english"
      contact: "contact-in-english"
    

    and when the app reload the routes, it will take the translations from your new locale, in this example from

    es:
      index: "index-in-spanish"
      contact: "contact-in-spanish"
    

    This way you it will render pages#index and pages#contact and it'll only change the route, you don't have to touch your code. Hope this helps you

提交回复
热议问题