我知道 i18n 语言环境文件中有一些预设结构,以便 Rails 自动提取值。例如,如果您想为新记录设置默认提交按钮文本:
# /config/locales/en.yml
en:
helpers:
submit:
create: "Create %{model}"
user:
create: "Sign Up"
通过此设置,在视图中将产生以下结果:
# /app/views/things/new.html.erb
<%= f.submit %> #=> Renders a submit button reading "Create Thing"
# /app/views/users/new.html.erb
<%= f.submit %> #=> Renders a submit button reading "Sign Up"
因此,Rails 使用预设的层次结构来获取不同模型的提交按钮文本。 (即,在使用时您不必告诉它要获取哪个 i18n 文本f.submit
.)我一直在尝试找到一种方法来通过闪光通知和警报来做到这一点。是否有类似的预设结构来指定默认的 Flash 消息?
我知道您可以指定自己的任意结构,如下所示:
# /config/locales/en.yml
en:
controllers:
user_accounts:
create:
flash:
notice: "User account was successfully created."
# /app/controllers/users_controller.rb
def create
...
redirect_to root_url, notice: t('controllers.user_accounts.create.flash.notice')
...
end
但指定它很乏味notice: t('controllers.user_accounts.create.flash.notice')
每次。有没有办法做到这一点,以便控制器“只知道”何时抓取并显示区域设置文件中指定的适当的闪存消息?如果是这样,它们的默认 YAML 结构是什么?
The Rails i18n 指南第 4.1.4 节有关“惰性”查找 http://guides.rubyonrails.org/i18n.html#looking-up-translations says:
Rails 实现了一种方便的方式来查找内部语言环境views
(强调他们的观点,至少向我暗示,它仅限于观点......)但是,似乎这对 Rails 的承诺 https://github.com/rails/rails/pull/7082/files还将“惰性”查找引入控制器中,密钥的形式为:
"#{ controller_path.gsub('/', '.') }.#{ action_name }#{ key }"
在你的情况下应该让你users.create.notice
.
所以,如果您对以下内容感到满意:
# /app/controllers/users_controller.rb
def create
...
redirect_to root_url, notice: t('.notice')
...
end
您应该能够在以下位置声明该值:
# /config/locales/en.yml
en:
users:
create:
notice: "User account was successfully created."
我知道这并不会让你完全拥有一个默认位置,Rails 会在创建用户失败时自动获取一个闪存通知,但这比每次都输入完整的 i18n 键要好一些。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)