使用Rails实现静态页面的国际化

Gav*_*vin 6 routes ruby-on-rails internationalization ruby-on-rails-3

我觉得我错过了一些非常简单的事情,我一直在努力解决这个问题.

我目前在我的应用程序中都有国际化工作.翻译工作和路线完美运作.至少,除了我的两个静态页面的路线,我的"关于"和"常见问题"页面之外,大多数网站都可以使用.

整个应用程序中的每个其他链接指向适当的本地化路线.例如,如果我选择"french"作为我的语言,链接指向相应的"(/:locale)/controller(.:format)." 但是,尽管我在整个应用程序中进行了更改,但我的"关于"和"常见问题解答"的链接拒绝指向"../fr/static/about"并始终指向"/ static/about".

为了让事情变得更奇怪,当我运行rake路线时,我看到:"GET(/:locale)/static/:permalink(.:format)pages#show {:locale =>/en | fr /}"

当我手动输入"../fr/static/about"时,页面翻译完美.

我的路线文件:

 devise_for :users

 scope "(:locale)", :locale => /en|fr/ do
  get 'static/:permalink', :controller => 'pages', :action => 'show'  

  resources :places, only: [:index, :show, :destroy]
  resources :homes, only: [:index, :show]

  match '/:locale' => 'places#index'
  get '/'=>'places#index',:as=>"root"
 end
Run Code Online (Sandbox Code Playgroud)

我的ApplicationController:

before_filter :set_locale

def set_locale
  I18n.locale=params[:locale]||I18n.default_locale
end
def default_url_options(options={})
  logger.debug "default_url_options is passed options: #{options.inspect}\n"
  { :locale => I18n.locale }
end
Run Code Online (Sandbox Code Playgroud)

和我的页面控制器:

class PagesController < ApplicationController
  before_filter :validate_page
  PAGES = ['about_us', 'faq']

  def show    
   render params[:permalink]
  end

 def validate_page
  redirect_to :status => 404 unless PAGES.include?(params[:permalink])
 end
end
Run Code Online (Sandbox Code Playgroud)

我会非常感谢任何帮助...这只是其中的一天.

编辑:感谢Terry慢跑我包含观点.

<div class="container-fluid nav-collapse">
    <ul class="nav">
      <li class="dropdown">
        <a href="#" class="dropdown-toggle" data-toggle="dropdown"><%= t(:'navbar.about')   %><b class="caret"></b></a>
          <ul class="dropdown-menu">  
            <li><%=link_to t(:'navbar.about_us'),  "/static/about_us"%></li>
            <li><%=link_to t(:'navbar.faq'),       "/static/faq"%></li>
            <li><%=link_to t(:'navbar.blog'),      '#' %></li> 
          </ul>  
      </li>
Run Code Online (Sandbox Code Playgroud)

Iva*_*der 4

您应该通过“as”为您的路线命名:

scope "(:locale)", :locale => /en|fr/ do
  get 'static/:permalink', to: 'pages#show', as: :static  
Run Code Online (Sandbox Code Playgroud)

然后在视图中使用路由助手(route_name_path)构建链接:

<li><%=link_to t('navbar.about_us'), static_path(permalink: "about_us") %></li>
Run Code Online (Sandbox Code Playgroud)

该助手会自动将当前区域设置添加到路径中。

要获取所有带有名称的路由列表,请使用rake paths控制台命令。

祝你好运!