Guilherme Oderdenge
Guilherme Oderdenge

Reputation: 5001

Remove "?locale=en" from URL

The goal

Remove ?locale=en of browser's URL bar when I click on a link.

Note: there's no any asynchronous mechanism behind the process. I mean, there's no window.history.pushState modifying URL dynamically when I click something.

The problem

Everything I'm doing isn't solving my problem.

What I've tried

I'm still searching further solutions.

Scenario

I don't want to have a localized admin panel, then, my routing are the following:

scope '/(:locale)', locale: /#{I18n.available_locales.join("|")}/ do
  root to: 'welcome#index'
end

namespace :admin do
  get '/' => 'home#index'

  resources :products
end

But I'm still always getting ?locale=en when I click on a link inside the admin's panel. This is how I set the locale:

# /app/controllers/application_controller.rb
def set_locale
  extracted_locale = params[:locale] || extract_locale_from_accept_language_header

  I18n.locale = (I18n::available_locales.include? extracted_locale.to_sym) ? 
                extracted_locale : I18n.default_locale
end

This is my private extract_locale_from_accept_language_header method:

# /app/controllers/application_controller.rb
private
def extract_locale_from_accept_language_header
  request.env['HTTP_ACCEPT_LANGUAGE'].scan(/^[a-z]{2}/).first
end

Diagnose reaction

If I change this:

I18n.locale = (I18n::available_locales.include? extracted_locale.to_sym) ? 
              extracted_locale : I18n.default_locale

for this:

I18n.locale = params[:locale] || I18n.default_locale

the issue is partially solved. Unfortunately, this is not what I really want. I'm dealing with browser's language if there's no other option to resolve the user's locale (a.k.a. URL's locale-parameter is explicitly set).

Upvotes: 1

Views: 1824

Answers (1)

ABMagil
ABMagil

Reputation: 5595

You want to look at the default_url_options method in your application controller. This is what determines how link_to creates urls, I18n.locale just controls a server-side setting. If you have a easy definition for all the pages which shouldn't get locale parameter, use it there. For instance,

def default_url_options(options={})
  if params[:controller].include? "admin"
    locale: nil
  end
end

Upvotes: 2

Related Questions