[Rails Tip] Making i18n Forms, the Easy Way

March 08, 2010|2 Min Read|Comments|

Web applications normally have many forms. Building forms is always a mind-boggling task because it involves repetition and chaos.

A shortcut is to use a form builder / DSL, such as Formtastic.

As I am using Rails 3, and the Rails 3 port of Formtastic isn’t complete yet, I thought I’d just use the plain vanilla Rails built-in form helper.

First of all, I am using Haml instead of ERb. Already, I got the out-of-box clean looking Haml markup.

Some of you might not be aware of the fact that Rails’ built-in form helper already does i18n support.

If you have the following form:

-form_for(@post) do |f|
  =f.label :title
  =f.text_field :title
  =f.label :body
  =f.text_area :body

You can simply translate the labels as such in config/locales/en.yml.

      title: "Post Title"
      body: "Post Content"

Better yet, I am using r18n instead of i18n, so I can instead translate them in app/i18n/en.yml.

      title: Post Title
      body: Post Content

Alternatively, instead of placing the translation strings under helpers.label, you may place them directly under your models, i.e. activemodel.attribute.

If you’re using the Rails 2.3 stable branch from Github, you can also use the built-in i18n support. Although instead of helpers.label, you use views.labels, as seen in this commit.

< Back to Blog