6

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!"
mu is too short
  • 426,620
  • 70
  • 833
  • 800
patrick
  • 9,290
  • 13
  • 61
  • 112

1 Answers1

8

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.

mu is too short
  • 426,620
  • 70
  • 833
  • 800
  • I tried finding this interpolation thing, good to have the link. – rubish Aug 24 '11 at 03:10
  • 1
    Hmmm.. Ok. I was hoping for an easy way to have values automatically interpolated without having to supply them as an argument to the calls to I18n.translate... – patrick Aug 28 '11 at 22:14
  • 2
    @patrick: That would lead to all sorts of crazy non-local behavior and strange bugs. Too much magic is a bad thing. – mu is too short Aug 28 '11 at 22:32