wazZzif
wazZzif

Reputation: 65

Symfony2: fetching all translations under a parent

In symfony2 controller you can fetch a specific translation using: $this->get('translator')->trans('dropdown.state.CA.AB');

Example messages.en.yml:

dropdown:
    state:
        CA:
            AB: Alberta
            BC: British Columbia
            MB: Manitoba

How can I fetch AB, BC and MB in one single call (in an array maybe) and hopefully also be able to call it individually using the above or a similar translation call.

Couple of things I have tried:

$this->get('translator')->trans('zuora.dropdown.state.CA);

dropdown:
    state:
        CA:
            - AB: Alberta
            - BC: British Columbia
            - MB: Manitobavarious

Surely, missing some step

Upvotes: 3

Views: 2156

Answers (1)

Touki
Touki

Reputation: 7525

No, you cannot get it through the translator.
This is because of ArrayLoader flattens the result of the parsed yml.

Flatten method transforms inputs like

Array (
    [foo] => Array(
        [bar] => baz
        [sub] => Array(
            [fiz] => foobaz
        )
    )
)

To

Array (
    [foo.bar] => baz
    [foo.sub.fiz] => foobaz
)

The only way I could find, is to parse again the translation file.

use Symfony\Component\Yaml\Yaml;

// From a controller
$file   = __DIR__.'/../Resources/translations/messages.en.yml';
$parsed = Yaml::parse(file_get_contents($file));

foreach ($parsed['dropdown']['state']['CA'] as $ca => $content) {
    // Your logic...
}

Upvotes: 2

Related Questions