Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Referencing translation inside of another translation

I have this situation:

unit:
    sqkm: Square Kilometers

my_translation: Size is %size% ## I want to append the value of unit.sqkm here ##

Is there a way to reference the translation of the unit.sqkm inside the my_translation key?

Edit: Please note that i do know how i can do this via twig. My question is: is there a way to do this in the translation files.

like image 707
smoove Avatar asked Jan 10 '13 12:01

smoove


2 Answers

I extended Symfony Tanslator for this:

<?php

namespace Bundle\Program\Translation;

use Symfony\Bundle\FrameworkBundle\Translation\Translator as BaseTranslator;

class Translator extends BaseTranslator
{
    /**
     * Uses Symfony Translator to translate, but enables referencing other translations via @@code@@
     */
    public function trans($id, array $parameters = array(), $domain = null, $locale = null)
    {
        $text = parent::trans($id, $parameters, $domain, $locale);

        $translations = [];

        $delimiter = "@@";
        $strLen = strlen($delimiter);
        $pos = strpos($text, $delimiter);

        while ($pos !== false) {
            $startsAt = $pos + $strLen;
            $endsAt = strpos($text, $delimiter, $startsAt);
            $translations[] = $delimiter . substr($text, $startsAt, $endsAt - $startsAt) . $delimiter;
            $pos = strpos($text, $delimiter, $endsAt + $strLen);
        }

        foreach ($translations as $translation) {
            $translationTrim = str_replace($delimiter, '', $translation);
            $text = str_replace($translation, $this->trans($translationTrim, $parameters, $domain, $locale), $text);
        }

        return $text;
    }
}

Then replace the Symfony translator class via parameters:

parameters:

    translator.class: Bundle\Program\Translation\Translator

Now you can reference other translations via @@other.translation@@ INSIDE your yml file.

like image 84
Kim Avatar answered Sep 28 '22 08:09

Kim


In your Twig template, try this :

{{ 'my_translation' | trans({'%size%': size, 'unit.sqkm' : ('unit.sqkm'|trans)}) }}
like image 33
AlterPHP Avatar answered Sep 28 '22 08:09

AlterPHP