Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

ruby - is there a way to reference a constant in a yaml with rails?

Is there a way to have my en.yml file contain a constant?

# en.yml
foo:
  bar:
    I love BAZ so much!

# initializers/constants.rb
BAZ = "stackoverflow.com"

I18n.t("foo.bar")
->  "I love stackoverflow.com so much!"

?

If not, is there a way to self reference the yaml file?

foo:
  bar:
    I love *baz* so much!
baz:
  stackoverflow.com

I18n.t("foo.bar")
->  "I love stackoverflow.com so much!"
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The I18N string tools support interpolation:

I18n.t('foo.bar', :baz => 'stackoverflow.com')

And then in the en.yml:

foo:
  bar:
    I love %{baz} so much!

Just don't try to use %{default} or %{scope} as variables in your strings, I18n.translate uses those for other things:

If a translation uses :default or :scope as an interpolation variable, an I18n::ReservedInterpolationKey exception is raised.

This doesn't apply to YAML in general but your question seems to be specifically about the translation files.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...