Question

Hi everyone in my app I build a search box. It looks like this:

= simple_form_for :cars, {url: cars_path, method: :get} do |f|
  = f.input :handover_location, collection: Location.all.map{|hl| [hl.name, hl.id]}
  = f.input :return_location, collection: Location.all.map{|rl| [rl.name, rl.id]}
  = f.input :car_class, collection: CarClass.all.map { |c| [c.name, c.id] }, include_blank: true
  = f.submit 

And now i don't know how to translate this labels with I18n. How can I do this?

Was it helpful?

Solution

Check the simple-form documentation regarding i18n: https://github.com/plataformatec/simple_form#i18n

It is pretty well described, and goes into great detail.

So for instance (from the documentation) :

en:
  simple_form:
    labels:
      defaults:
        username: 'User name'
        password: 'Password'
        new:
          username: 'Choose a user name'
    hints:
      defaults:
        username: 'User name to sign in.'
        password: 'No special characters, please.'
    placeholders:
      defaults:
        username: 'Your username'
        password: '****'

This specifies the defaults for labels. You should check the documentation, because there are a lot more options.

Secondly, you can also do it explicitly, like so

= f.input :car, label: I18n.t('my_car_label'), prompt: I18n.t('my-car-prompt'), placeholder: I18n.t('my-placeholder')

OTHER TIPS

First off, I'd begin by perusing the docs, particularly part 3. For forms based on active record models, Rails has some custom built-in support (see part 4.6 of the docs). For instance, to translate your Car model name to something other than "Car", you could do this:

# config/locales/en.yml
en:
  activerecord:
    models:
      car:
        one: Automobile
        other: Automobiles

(Substitute for your language of choice to support I18n.)

However, to use I18n in general, you'd call the translate method Rails provides, abbreviated by t. Example:

= simple_form_for :cars, {url: cars_path, method: :get} do |f|
  ..
  = f.label t('forms.car_class')
  = f.input :car_class, collection: CarClass.all.map { |c| [c.name, c.id] }, include_blank: true
  ..
  = f.submit 

# config/locales/en.yml

en:
  forms:
    car_class: 'Automobile'

Which would render the label with the text: 'Automobile'.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top