Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I want to use variables declared in yml file right there. For example, I declared site_name and want to use it below in description.

en:
  site_name: &site_name "Site Name"
  static_pages:
    company:
      description: *site_name #this works fine
      description: "#{*site_name} is an online system" #this doesn't work

How can I combine *site_name variable with additional text?

question from:https://stackoverflow.com/questions/13055753/passing-variables-inside-rails-internationalization-yml-file

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

1 Answer

The short answer is, I believe, no you cannot do string interpolation in YAML the way you want using an alias.

In your case, what I would do is have something like the following in my locale file:

en:
  site_name: "Site Name"
  static_pages:
    company:
      description: ! '%{site_name} is an online system'

and then call in the appropriate view with the site name as a parameter:

t('.description', site_name: t('site_name'))

which would get you "Site Name is an online system".

However, if you're desperate to use aliases in your YAML file to concatenate strings together, the following completely unrecommended code would also work by having the string be two elements of an array:

en:
  site_name: &site_name "Site Name"
  static_pages:
    company:
      description:
        - *site_name
        - "is an online system"

and then you would join the array in the appropriate view like this:

t('.description').join(" ")

Which would also get you "Site Name is an online system".

However, before you decide to go down this path, apart from the question that @felipeclopes linked to, have a look at:

  • this StackOverflow answer regarding concatenating i18n strings (tl;dr Please don't for your translation team's sake).
  • StackOverflow questions here and here that are similar to your question.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...