Ajay
Ajay

Reputation: 91

How can we pass a variable and use it inside a yml file

I need to perform string interpolation inside yml file, to create a custom error message based on a value which I will pass to locale yml file.

something like

users:
  error1: "custom error message based on variable #{passed_in_var}"

Is this possible?

Upvotes: 4

Views: 1958

Answers (2)

konyak
konyak

Reputation: 11706

If you use .yml.erb, you can bind variables to ERB. Ref: https://ruby-doc.org/stdlib-2.6/libdoc/erb/rdoc/ERB.html

variable1 = "text1"
variable2 = "text2"
ERB.new(template).result(binding)

This will use the current block's context to interpolate the variables in the ERB template.

Upvotes: 0

Sergio Tulentsev
Sergio Tulentsev

Reputation: 230286

Use I18n interpolation!

users:
  error1: "custom error message based on variable %{passed_in_var}"

Then you call it like this:

t('users.error1', passed_in_var: 'foobar')

Upvotes: 6

Related Questions