2015-05-29 65 views
3

我目前正在研究一個有2個不同的本地語言(nl/fr)的項目。切換當前頁面導軌上的語言環境

我們面臨這樣的問題:我如何獲得當前頁面的轉變的URL,當我顯示FR/NL按鈕

我目前正在friendly_id工作和全球化

我們已經試過:

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

都工作來改變當前的語言,但正如我們所friendly_url,當頁面在法國被加載(本地主機:3000/C/ANIMAUX)

我們應該有

localhost:3000/nl/c/dieren 

代替

localhost:3000/nl/c/animaux 

我有這麼多的鏈接來翻譯,所以我希望有一個railsway做到這一點。

+0

「animaux」是否存儲在slug列中,即將到來從你的數據庫? – Surya

+0

對不起,我沒有仔細閱讀這個問題,它不是重複的。 – max

+0

是它存儲在全球化的數據庫中: **表類別:**'name_fr:animaux' | 'name_nl:dieren' – Thounder

回答

1

你既可以通過資源url_for:

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

如果是太多重複代碼,你可以創建一個幫助:

# 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 

另一種方法是使用I18n.with_locale,它可以讓你在另一個區域運行一個塊:

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

嗯,感謝你的回答,你讓我成爲解決方案的一部分,我會弄清楚我自己的其餘部分。 '= link_to「nl」,params.merge(locale:「nl」,id:@ resource.id)' – Thounder

相關問題