Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I translate placeholder text in Rails 4?

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?

like image 723
Jumbalaya Wanton Avatar asked Sep 05 '14 00:09

Jumbalaya Wanton


2 Answers

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"
like image 168
cweston Avatar answered Oct 16 '22 01:10

cweston


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'}"
like image 25
blackchestnut Avatar answered Oct 16 '22 01:10

blackchestnut