Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails / I18n: default scope

I'm using the default I18n module for Rails to translate my strings in views.

<%= t("registration.heading") %>

Now, when I'm in the registration-view, all my strings start with registration. I always have to write

<%= t("registration.heading.notice") %>
// or
<%= t(:heading, :scope => :registration) %>

It would be nice to define a default scope for that file (maybe even in the controller), so a call to t automatically adds the defined scope

// controller
set_i18n_default_scope :registration

// view
<%= t(:heading) %>

// --> looks in "registration.heading"

Is this possible?

like image 566
Markus Avatar asked May 26 '11 11:05

Markus


3 Answers

If you organize your translations adding a view name, as in:

en:
  registration:
    index:
      heading: "Registration heading"

then you may use this:

<%= t(".heading") %>

Notice that the first character is a dot.

You may read about it in Rails Internationalization (I18n) API Guide

If you have texts which are shared amongst numerous views, and you don't want to copy the same translation in each section for each view, you may use YAML references. They are nicely described on wikipedia: http://en.wikipedia.org/wiki/YAML#Repeated_nodes

like image 87
Arsen7 Avatar answered Nov 16 '22 22:11

Arsen7


It is possible. Check section 4.1.4 of the Rails i18n API

4.1.4 “Lazy” Lookup

Rails 2.3 implements a convenient way to look up the locale inside views. When you have the following dictionary:

  es:   books:
          index:
             title: "Título" 

you can look up the books.index.title value inside

app/views/books/index.html.erb template like this (note the dot):

<%= t '.title' %>
like image 33
bruno077 Avatar answered Nov 17 '22 00:11

bruno077


Regarding Lazy Lookups:

Here's the general solution for this kind of problem

Common Problem: Where is Rails trying to look-up L10N / I18N Strings? - e.g. when doing Lazy Lookups

It's not easy to guess, because it's different for Views, Controllers, Models, Labels, Helpers, or Validations... etc... but...

It's easy to find out directly, using this:

http://www.unixgods.org/Rails/where_is_Rails_trying_to_lookup_L10N_strings.html

this helps figuring out what Rails thinks the current scope is (e.g. when using ".heading")

3 Simple Steps:

  1. create a file ./config/initializers/i18n.rb , as described in the article above
  2. put t('.heading') in your view
  3. start "rails server" and look in the console output where Rails thinks the default location is for '.heading' for this view... e.g. what's the I18N-key

(4. then add the I18N string into the location identified by the key)

Works like a charm :-)

like image 40
Tilo Avatar answered Nov 16 '22 22:11

Tilo