8

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?

japysha
  • 121
  • 8

2 Answers2

3

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)
Community
  • 1
  • 1
ferdynator
  • 6,245
  • 3
  • 27
  • 56
1

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}) }}
cheesemacfly
  • 11,622
  • 11
  • 53
  • 72
  • 1
    Thanks, but I want to avoid this step in twig. In this example I would like to use _my_favorite_website_ directly in translation and call it in twig without passing any value: `{{ 'I.love.website'|trans() }}` – japysha Jul 23 '13 at 06:47
  • 1
    Mmmmh I am afraid there is no simple solution to do this. The translation service requires that you pass the placeholder in an `array()` as a second parameter when calling it so it is more a translate service "limitation" than a twig one. You could probably write a twig extension if the placeholder is always the same but that would be a dirty trick... – cheesemacfly Jul 23 '13 at 14:15