Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use config value in symfony2 translation?

Is it possible to use global variable from config.yml in translation file in symfony 2? If yes, please can you give some example or useful link?

like image 381
japysha Avatar asked Jul 19 '13 09:07

japysha


2 Answers

For injecting a (or all) twig globals into your translations you need to override the translation service. Check out this answer if you want a detailed explanation. Here is what I did:

Override the translator.class parameter (e.g. in your parameters.yml):

translator.class:  Acme\YourBundle\Translation\Translator

Create the new Translator service:

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

class Translator extends BaseTranslator
{

}

Finally override both trans and transChoice:

/**
 * {@inheritdoc}
 */
public function trans($id, array $parameters = array(), $domain = null, $locale = null)
{
    return parent::trans(
        $id,
        array_merge($this->container->get('twig')->getGlobals(), $parameters),
        $domain,
        $locale
    );
}

/**
 * {@inheritdoc}
 */
public function transChoice($id, $number, array $parameters = array(), $domain = null, $locale = null)
{
    return parent::transChoice(
        $id,
        $number,
        array_merge($this->container->get('twig')->getGlobals(), $parameters),
        $domain,
        $locale
    );
}

In this example I am injecting all twig globals. You can only inject one like this:

array_merge(['%your_global%' => $this->container->get('twig')->getGlobals()['your_global']], $parameters)
like image 54
ferdynator Avatar answered Nov 05 '22 08:11

ferdynator


You can follow those 2 simple steps:

  1. Inject a Global variable in all the templates using the twig configuration:

    # app/config/parameters.yml
    parameters:
        my_favorite_website: www.stackoverflow.com
    

    And

    # app/config/config.yml
    twig:
        globals:
            my_favorite_website: "%my_favorite_website%"
    
  2. Use Message Placeholders to have the ability to place your text in your translation:

    # messages.en.yml
    I.love.website: "I love %website%!!"
    
    # messages.fr.yml
    I.love.website: "J'adore %website%!!"
    

You now can use the following twig syntax in your templates to get your expected result:

{{ 'I.love.website'|trans({'%website%': my_favorite_website}) }}
like image 28
cheesemacfly Avatar answered Nov 05 '22 09:11

cheesemacfly