我知道 i18n 语言环境文件中有一些预设结构,以便 Rails 自动提取值。例如,如果您想为新记录设置默认提交按钮文本:
# /config/locales/en.yml
en:
helpers:
submit:
create: "Create %{model}"
user:
create: "Sign Up"
使用此设置,在 View 中将产生以下结果:
# /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 使用预设的层次结构来获取不同模型的提交按钮文本。 (即,使用 f.submit
时,您不必告诉它要获取哪个 i18n 文本。)我一直在尝试找到一种方法来通过 Flash 通知和警报来实现此目的。是否有类似的预设结构来指定默认的 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')
非常繁琐。有没有办法做到这一点,以便 Controller “只知道”何时抓取并显示区域设置文件中指定的适当的闪存消息?如果是这样,它们的默认 YAML 结构是什么?
最佳答案
Rails i18n guide section 4.1.4 on "lazy" lookups说:
Rails implements a convenient way to look up the locale inside views
(强调他们的观点,至少向我暗示,它仅限于 View ......)但是,似乎 this commit to Rails也将“惰性”查找引入 Controller , key 的形式为:
"#{ 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 会在创建用户失败时自动获取一个 Flash 通知,但这比每次都输入完整的 i18n key 要好一些。时间。
关于ruby-on-rails - 在 Rails 中,如何在 i18n 语言环境文件中指定默认 flash 消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22467734/