How to use configuration value in symfony2 translation?

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

+7
php symfony translation
source share
2 answers

You can follow these two simple steps:

  • Enter the Global variable in all templates using the branch 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%" 
  • Use the "Hostages of Messages" to be able to place text in your translation:

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

Now you can use the following twig syntax in your templates to get the expected result:

 {{ 'I.love.website'|trans({'%website%': my_favorite_website}) }} 
+1
source share

To enter the globule (or all) twig into your translations, you need to redefine the translation. Check this answer if you want a detailed explanation. Here is what I did:

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

 translator.class: Acme\YourBundle\Translation\Translator 

Create a new Translator service:

 use Symfony\Bundle\FrameworkBundle\Translation\Translator as BaseTranslator; class Translator extends BaseTranslator { } 

Finally, replace 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 enter all. You can enter only one:

 array_merge(['%your_global%' => $this->container->get('twig')->getGlobals()['your_global']], $parameters) 
+1
source share

All Articles