Redirect same page to different language with Globalize & Friendly_id

三世轮回 提交于 2019-12-07 01:07:10

问题


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:


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) }


来源:https://stackoverflow.com/questions/28226949/redirect-same-page-to-different-language-with-globalize-friendly-id

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!