Search code examples
ruby-on-railsrubyfriendly-idglobalize

Switch locale on current page rails


i'm currently working on a project which has 2 different locals (nl/fr).

We're facing this problem : How can I get the translated url for the current page when I display fr/nl button

I'm currently working with friendly_id and globalize

we've tried :

= link_to "nl", params.merge(locale: "nl")
= link_to "nl", url_for(:locale => :nl)

both work to change the current language but as we've friendly_url, when the page is loaded in french (localhost:3000/c/animaux)

we should have

localhost:3000/nl/c/dieren

instead of

localhost:3000/nl/c/animaux 

I've so many link to translate so I wish there's a railsway to do this.


Solution

  • You could either pass the resource to url_for:

    = link_to "nl", params.merge(locale: "nl", id: @resource.id)
    

    If that is too much code duplication you could create a helper:

    # Try to guess the resource from controller name
    # @param [String] locale
    # @param [Hash] options - passed on to url_for
    #   @option options [String] :text the text for the link
    #   @option options [Object] :resource the model to link to.
    def page_in_other_locale(locale, options = {})
      opts = params.dup.merge(options).merge(locale: locale)
      text = opts[:text] || locale     
      resource = nil
    
      if opts[:resource] 
        resource = opts[:resource]
      else
        resource = controller.instance_variable_get?(":@#{controller_name.singularize}")
      end
    
      opts.merge!(id: resource.try(:id)) if resource
      link_to(text, opts.except(:text, :resource))
    end
    

    Another alternative is to use I18n.with_locale, it lets you run a block in another locale:

    I18n.with_locale(:nl) do
      link_to('nl', params.merge(id: category.name))
    end