编写一个完全翻译的应用程序可能会变得枯燥乏味。是否有方法为当前上下文设置默认的翻译范围?
示例:我正在用我的_deadlines.html.erb的show.html.erb操作在部分ProjectsController中编写
现在,因为我试图成为一个好的程序员,我正在界定我所有的翻译。我想要生产以下的树
projects:
deadlines:
now: "Hurry the deadline is today !"
....我怎样才能使它比每次写完整的范围要少一些乏味呢?
projects/show.html.erb
...
<%= render 'projects/deadlines', project: @project %>
...show.html.erb调用的projects/_dellines.html.erb
<p>Deadline : <%= t(:now, scope: [:projects, :deadlines]) %></p>是否有方法为当前上下文(这里是整个_deadlines.html.erb文件)设置默认范围?
编辑
有些人建议使用Rails 懒惰查找,但这并不能产生我正在寻找的范围。在我的例子中,我想跳过action默认范围(显示、索引等)并为当前呈现的部分添加一个作用域(在我的示例中是_deadlines.html.erb)
Rails懒散查找:
t('.now')
<=> t(:now, scope: [:projects, :show]但我想:
t('.now')
<=> t(:now, scope: [:projects, :deadlines]发布于 2015-05-17 15:38:07
好吧我还是对此不满意。当您想在不同的地方翻译相同的东西时,这个默认的‘懒惰查找’范围完全是krap。假设我有两个不同的部分,包含处理同一个模型的信息。使用惰性查找,我需要在yml文件中进行两次相同的翻译。
下面是您可以在应用程序助手中放入的一小部分代码。它基本上是默认I18n.t的一种覆盖,它在定义范围时将作用域设置为@t_scope,您不再需要担心范围了
我的代码添加
助理员/应用程序.
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你能用它做什么
projects/show.html.erb
<%= t_scope([:projects, :deadlines]) %>
<fieldset>
<legend>Deadlines</legend>
<% if Time.now > @project.deadline.expected_finish_date %>
<p><%= t(:hurry) %></p>
<% else %>
<p><%= t(:you_have_time) %>
</fieldset>
<fieldset>
<legend>Deadlines</legend>
<%= render 'tasks', tasks: @project.tasks %>
...视图/项目/_tasks.html.erb
<%= t_scope([:projects, :tasks]) %>
<% tasks.each do | task| %>
<h2><%= t(:person_in_charge) %></h2>
...
<% 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设置为零
发布于 2015-02-19 16:00:45
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"发布于 2021-04-20 14:46:19
由于t('.foo')是可能的,并且可能有选项(例如,插值),下面是我改进前一个的建议
def t(*args, **kwargs)
if args.size == 1 and (args.first.is_a?(Symbol) || args.first.to_s.start_with?('.') ) and @t_scope
I18n.t(args.shift, kwargs.reverse_merge!(@t_scope))
else
I18n.t(*args)
end
endhttps://stackoverflow.com/questions/28595913
复制相似问题