Rails I18n翻译范围

编写完全翻译的应用程序可能会变得乏味。 有没有办法为当前上下文设置默认转换范围?

示例:我正在我的ProjectsControllershow.html.erb操作中写入部分_deadlines.html.erb

现在,因为我想成为一名优秀的程序员,所以我的所有翻译都是如此。 我想生成以下树

 projects: deadlines: now: "Hurry the deadline is today !" .... 

我怎样才能比每次写完整个范围时更省力?

项目/ show.html.erb

 ...  ... 

show.html.erb调用的projects / _deadlines.html.erb

 

Deadline :

有没有办法为当前上下文设置默认范围(这里是整个_deadlines.html.erb文件)?

编辑

有些人建议使用Rails Lazy查找 ,但这不会产生我正在寻找的范围。 在我的情况下,我想跳过action默认范围(显示,索引等…)并为我正在呈现的当前部分添加范围(在我的情况下为_deadlines.html.erb)

Rails懒惰查找:

 t('.now')  t(:now, scope: [:projects, :show] 

但我想:

 t('.now')  t(:now, scope: [:projects, :deadlines] 

Rails实现了在视图中查找区域设置的便捷方式。 当你有以下字典时:

 es: projects: index: # in 'index.html.erb' template file title: "Título" deadlines: # in '_deadlines.html.erb' partial file title: "Fecha límite" 

您可以按以下方式查找这些值:

 # app/views/projects/index.html.erb <%= t '.title' %> # => "Título" # app/views/projects/_deadlines.html.erb <%= t '.title' %> # => "Fecha límite" 

好吧,我还是不满意。 当你想在不同的地方翻译同一个东西时,这个默认的“懒惰查找”范围完全是废话。 假设我有两个不同的部分包含处理相同模型的信息。 使用延迟查找,我需要在我的yml文件中进行两次相同的翻译。

这里有一小段代码可以放在应用程序帮助器中。 它基本上是默认I18n.t的覆盖,它将在定义范围时将范围设置为@t_scope ,并且您不再需要担心范围

我的代码添加

助手/ application_helper.rb

 def t(*args) # If there is just one param and we have defined a translation scope in the view # only using symbols right now, need extended version to handle strings if args.size == 1 and args.first.is_a?(Symbol) and @t_scope super(args.shift, @t_scope) else super(*args) end end def set_t_scope(scope) push_t_scope(@t_scope ||= {}) replace_t_scope(scope) end alias :t_scope :set_t_scope def replace_t_scope(scope) @t_scope = {scope: scope} end def push_t_scope(scope) (@tscope_stack ||= []) << scope end def pop_t_scope @t_scope = @tscope_stack.pop end 

你可以用它做什么

项目/ show.html.erb

 <%= t_scope([:projects, :deadlines]) %> 
Deadlines <% if Time.now > @project.deadline.expected_finish_date %>

<%= t(:hurry) %>

<% else %>

<%= t(:you_have_time) %>

Deadlines <%= render 'tasks', tasks: @project.tasks %> ...

意见/项目/ _tasks.html.erb

 <%= t_scope([:projects, :tasks]) %> <% tasks.each do | task| %> 

<%= t(:person_in_charge) %>

... <% pop_t_scope %>

en.yml

 en: projects: deadlines: hurry: "Hurry man !" you_have_time: "Relax, there's still time" tasks: person_in_charge: 'The Boss is %{name}' 

现在我唯一看到的问题是,当从视图中渲染多个部分时,@ t_scope将被转移并可能导致问题。 但是,在每个文件的开头将@t_scope设置为nil不会有问题