Search code examples
phpsymfonyinternationalizationtranslationsymfony4

Symfony 4 translations component translate by id not working


When I call function $translator->trans($key), the doc states that the first parameter is the id. To me it seems that the id should relate to the id attribute inside the .xlf file. In reality, it relates to the source element of the .xlf file.

Method call inside controller:

$translator->trans('KUNGFU.CODER')

messages.en.xlf (EN) which does NOT work with the method call above:

<?xml version="1.0"?>
<xliff version="1.2" xmlns="urn:oasis:names:tc:xliff:document:1.2">
    <file source-language="nl" datatype="plaintext" original="file.ext">
        <body>
            <trans-unit id="KUNGFU.CODER">
                <source>De code fu is sterk bij deze</source> // dutch source message
                <target>The code fu is strong inside this one</target>
            </trans-unit>
        </body>
    </file>
</xliff>

messages.en.xlf (EN) which does work with the method call above:

<?xml version="1.0"?>
<xliff version="1.2" xmlns="urn:oasis:names:tc:xliff:document:1.2">
    <file source-language="nl" datatype="plaintext" original="file.ext">
        <body>
            <trans-unit id="KUNGFU.CODER">
                <source>KUNGFU.CODER</source> // id
                <target>The code fu is strong inside this one</target>
            </trans-unit>
        </body>
    </file>
</xliff>

I could of course go ahead and use the second option everywhere but it seems wrong. What am I missing here?


Solution

  • Fair warning going with option 2 can make using translations editors tricky. Because when you go to translate it the source will show the id instead of the words to be translated.

    An alternative that I use is option 1, but instead of putting the id in the id field put it as a resname="". Symfony will use this resname and the translation file will make a little more sense because most programs people expect the source to be words you want.

    If you already have a large xlif file without resnames I add one resname to the first item then use "Easy XML Editor" in table view to copy all the id's to the resname column, takes a minute or so to do.

    My two cents.

    Matt