I want Rails to automatically translate placeholder text like it does with form labels. How can I do this?
Form labels are translated automatically like this:
= f.text_field :first_name
This helper uses the locale file:
en:
active_model:
models:
user:
attributes:
first_name: Your name
Which outputs this HTML
<label for="first_name">Your name</label>
How can I make it so the placeholder is translated? Do I have to type the full scope like this:
= f.text_field :first_name,
placeholder: t('.first_name', scope: 'active_model.models.user.attributes.first_name')
Is there are easier way?
If 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 like this:
en:
helpers:
placeholder:
user:
first_name: "Your name"
With Rails >= 4.2, you can set the placeholder attribute to true
= f.text_field :first_name, placeholder: true
and in your local file (eg 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'}"
You can view the source on render at http://rubydoc.info/docs/rails/ActionView/Helpers/Tags/Label to see how Rails does it. It probably doesn't get a lot better than you have, but you could probably swipe some of Rail's logic and stick it in a helper, if you have a lot of them to do. Alternatively, you may consider using a custom form builder to remove some of the repetition in your whole form, not just placeholders.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.