Glory to Russia
Glory to Russia

Reputation: 18712

How to get the locale in the i18n file?

In my Sinatra-based project I have a login route:

# route to receive login form: sorry or logs in with cookie. sends home.
post '/login' do
    redirect to('/') if authorized?
    logger.info 'Params, password: ' + params[:password]
    sorry 'bademail' unless (/\A\S+@\S+\.\S+\Z/ === params[:email])
    sorry 'badlogin' unless String(params[:password]).size > 3
    logger.info 'Params, email: ' + params[:email]
    ok, p = @peepsdb.call('get_person_password', params[:email], params[:password])
    sorry 'badlogin' unless ok
    login p[:id]
    # redirect to('/')
    redirect to('/' + I18n.locale.to_s + '/main')
end

If something is wrong, e. g. the credentials, the user is directed to a page with a localized message. This happens using the sorry function:

get '/sorry' do
    @header = @pagetitle = 'Sorry!'
    @msg = case params[:for] 
    when 'bademail'
        I18n.t 'sorry_bademail'
    when 'unknown'
        I18n.t 'sorry_unknownemail'
    when 'badid'
        I18n.t 'sorry_badid'
    when 'badpass'
        I18n.t 'sorry_badpass'
    when 'badlogin'
        I18n.t 'sorry_badlogin'
    when 'badupdate'
        I18n.t 'sorry_badupdate'
    else
        I18n.t 'sorry_unknown'
    end
    erb :generic
end

The message is rendered using the following view:

<section id="generic">

<h1><%= @pagetitle %></h1>

<p><%= @msg %></p>

</section>

Some of the localized strings have URLs in them:

sorry_badlogin: 'That email address or password wasn’t right.</p><p>Please <a href="<%= I18n.locale %>/login">try again</a>.'

I need to direct the user to en/login URL (not /login) because our current i18n framework uses that prefix to determine the locale.

If I use the version above (<a href="<%= I18n.locale %>/login">), it doesn't work.

How can I insert the locale into the URL inside the file with localized texts? Is there any workaround?

Upvotes: 1

Views: 258

Answers (1)

Mihai Dinculescu
Mihai Dinculescu

Reputation: 20033

You should parameterize your error messages.

sorry_badlogin: 
  'That email address or password wasn’t right.</p><p>Please <a href="%s">try again</a>.

get '/sorry' do
    ---
    when 'bademail'
        (I18n.t 'sorry_bademail') % "#{I18n.locale}/login"
    ...
end

Upvotes: 1

Related Questions