3

On one of my contact form, there is a pre-filled message so the candidates avoid bad messages and have an initial good basis to work with.

So far I was using a single message_template, but I'd like to introduce some variety with a random list.

My translation needs some variables to work properly

Originally I had something like this

# locales/en.yml
en:
  message_template: "Hello %{name}, how are you on this %{day} !"

# my_view.html.erb
<%= t(:my_template, name: @user.name, day: DateTime.now.strftime('B') %>

I would like to switch to a random translation string (ie picking a random translation from a list), AND still replace the variables.

Something like

# locales/en.yml
en:
  message_templates: 
    - "Hello %{name}, how are you on this %{day} !"
    - "Hi %{name}, nice %{day} isn't it ? how are you ?"

# my_view.html.erb
<%= t('my_templates.sample'), name: @user.name, day: DateTime.now.strftime('B') %>

What would be a working syntax ?

NOTE :

I tried <%= t('my_templates, name: @user.name, day: DateTime.now.strftime('B')).sample %> But I obtain strings with param values not substituted :

Hi %{name}, nice %{day} isn't it ? how are you ?

Cyril Duchon-Doris
  • 12,964
  • 9
  • 77
  • 164

1 Answers1

2

I used a combo of sample, t and I18n.interpolate

<%= I18n.interpolate(
  t('my_templates').sample, 
  name: @user.name, 
  day: DateTime.now.strftime('B') 
%>
Cyril Duchon-Doris
  • 12,964
  • 9
  • 77
  • 164