How to translate placeholder text in Rails 4?

I want Rails to automatically translate placeholder text, as is done using form labels. How can i do this?

Form signs are automatically converted as follows:

= f.text_field :first_name 

This helper uses the locale file:

 en: active_model: models: user: attributes: first_name: Your name 

What this HTML outputs

 <label for="first_name">Your name</label> 

How can I do this so that the placeholder is translated? Should I enter the full volume as follows:

 = f.text_field :first_name, placeholder: t('.first_name', scope: 'active_model.models.user.attributes.first_name') 

Is there an easier way?

+5
source share
3 answers

When using Rails 4.2, you can set the placeholder attribute to true:

 = f.text_field :first_name, placeholder: true 

and specify the placeholder text in the locale file as follows:

 en: helpers: placeholder: user: first_name: "Your name" 
+11
source

You can view the source on the render at http://rubydoc.info/docs/rails/ActionView/Helpers/Tags/Label to see how Rails does it. This is probably not much better than yours, but you could probably do some Rail logic and stick with it in an assistant if you need to do a lot. In addition, you might consider using a custom form designer to remove some repetitions in the whole form, not just placeholders.

0
source

With Rails> = 4.2 you can set the placeholder attribute to true

= f.text_field :first_name, placeholder: true

and in your local file (e.g. en.yml):

 ru: activerecord: attributes: user: first_name: Your name 

otherwise (Rails> = 3.0) I think you can write something like this:

 = f.text_field :attr, placeholder: "#{I18n.t 'activerecord.attributes.user.first_name'}" 
0
source

Source: https://habr.com/ru/post/1201859/


All Articles