Question

Assuming that I have views/admin/, views/user/, controller/admin/, controller/user/ (etc) folders, what's the right way to structure my locales.yml file so it works properly?

Right now, it looks like this:

en:
  views:
    admin:
      index:
        phrase1: Text1
        phrase2: Text2
        ... 
      new:
      show:
      ...
    user:
      index:
      new:
      show:
  controllers:
    ...
    etc

But when I put, say, <%= t :phrase1 %> in the /views/admin/index.html.erb code, it doesn't work (neither this nor <%= t ".phrase1" %> so it's not a syntax error). However, if I place phrase1: Text1 just below the en: line (above any sub-dictionary), everything works just fine.

Was it helpful?

Solution

You have to use the key to get the translation. See it as a tree like structure. You have to tell the whole path to the final leaf.

In your case it is the following key:

"views.admin.index.phrase1"

For example we could have a translation file that looks like this:

en:
  home:
    salutation: "Welcome home"
  admin:
    salutation: "Welcome back master"

As you can see, we have two keys named salutation. If we used only "salutation" as key, it wouldn't be possible to tell which one we need.

Using the path home.salutation or admin.salutation makes it clear which text value we need.

Also, one reason why having to type the whole key is better than typing a part of it. Let say you are able to write a context dependent translation that will set a prefix to the key. When in controllers it adds: controllers. when in views views. and so on.

If you type the full key, you will always find where it is used in your project without problem.

If you start writing partial keys, like let say dog, you will find in the code every place where there is the word dog but not exactly controllers.home.dog. When it will be time to debug and change languages, you'll be quite happy to use a full key.

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