laravel / ideas

Issues board used for Laravel internals discussions.
938 stars 28 forks source link

Support for nested JSON translations #2525

Closed pascalbaljet closed 3 years ago

pascalbaljet commented 3 years ago

Currently, the Translator class does not support JSON files with nested objects. This is commented in the code as well:

For JSON translations, there is only one file per locale, so we will simply load that file and then we will be ready to check the array for the key. These are only one level deep so we do not need to do any fancy searching through it.

We're working on an Inertia/Vue app that uses translation files with a depth of more than one level:

en.json

{
    "product": {
        "name": "Product name",
        "sku": "SKU",
    }
}

For the Laravel backend, we wanted to use the same files, so I wrote some logic to support nested objects (from JSON files) in the Translator class. Before I submit a PR to bring this to the core, I wondered, is there a reason not to support this, as the limitation is explicitly noted in the code.

donnysim commented 3 years ago

Laravel JSON translations are not the same as php ones, its target is to be used as text keys:

{
    "Product name": "Translated product name",
    "SKU": "Translated SKU"
}

and you just write the actual text in code, not some kind of key, so when the text is not found in other language, you won't get product.name but Product name instead.

pascalbaljet commented 3 years ago

I know how the JSON implementation currently works, and even with the addition I've got in my mind, that would still work and wouldn't be breaking change. But in other libraries like Vue I18n, it's common to work with nested keys, as described in my initial post. My PR would bring support for that to Laravel so you can share JSON files between Laravel and, for instance, Vue.

donnysim commented 3 years ago

For sharing I can see the need, though I don't see why it would be hard to provide them via PHP (route or CLI) unless it has to be part of the compilation process. Though each to their their own experience, for me keyed translations never worked well once the app (SPA) grows large, so I'm kind of neither for nor against the idea so I'll leave it at that. I can see the need when used with keyed translations and I did find it strange at first that it resolved translations differently from PHP based ones.