Redirect same page to different language with Glob

2019-04-26 21:38发布

I've been scratching my head for the last few hours, looking for an answer but I can't find it anywhere.

My gem file:

# Use globalize for translating models
gem "globalize", github: "ncri/globalize" # for Rails 4.2
gem 'globalize-accessors', '~> 0.1.5'

# Use friendly_id for slugs
gem 'friendly_id', '~> 5.1.0'
gem 'friendly_id-globalize', '~> 1.0.0.alpha1'

Here's the situation:

I have two languages "en" and "fr"

2 models : pages and pages_translations pages has a slug column, pages_translations also has a slug column.

if I view the page -> en/pages/slug-en, it works.

if I view the page -> fr/pages-slug-fr, it works.

So I assume friendly_id and globalize are properly configured.

However my problem is that I can't make a language switcher work using:

  <% if I18n.locale != :en %>
    <li>
    <%= link_to t('menu.languages.short_en'), url_for(locale: 'en') %>
    </li>
<% end %>

The route becomes en/pages/slug-fr (i.e. the language changes but not the slug).

I have activated config.use :finders in the initializer.

My page model:

translates :title, :slug, :blurb, :content, :seo_title, :seo_description, :seo_keywords
  globalize_accessors :locales => [:en, :fr], :attributes => [:title, :slug, :blurb, :content, :seo_title, :seo_description, :seo_keywords]

    extend FriendlyId
      friendly_id :slug, :use => :globalize
      validates :slug, presence: true, uniqueness: { case_sensitive: false }

So what do I need to do to have the proper path on my language switcher? Ideally, I'd like this to work with any models, not just the Page model.

Thanks! - Vincent

1条回答
来,给爷笑一个
2楼-- · 2019-04-26 22:13

I believe you have url_for in your global layout, for different controllers. In that case, you have to set certain record in each controller (you can make helper or move everything into a router/middleware level). url_for(page) must be run in I18n.with_locale and might be require https://github.com/norman/friendly_id-globalize.

Some more info can be found here: https://github.com/norman/friendly_id-globalize/issues/7 and http://www.cantierecreativo.net/blog/2015/02/10/alternate-sitemap/ (in some language, but examples may help you to understand the whole concept).

TL;DR

# app/views/layouts/application.html.slim
ul.switch_locale
  - I18n.available_locales.each do |locale|
    li= I18n.with_locale(locale) do
      - url = yield(:current_page_url) || url_for(locale: locale)
      = link_to "Switch to #{locale}", url

# app/views/posts/show.html.slim
- content_for(:current_page_url) { post_url(@post) }
查看更多
登录 后发表回答