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
258 views
in Technique[技术] by (71.8m points)

Passing variables inside rails internationalization yml file

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

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

1 Reply

0 votes
by (71.8m points)

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.

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

...