简体   繁体   English

如何在symfony2翻译中使用配置值?

[英]How to use config value in symfony2 translation?

Is it possible to use global variable from config.yml in translation file in symfony 2? 可以在symfony 2的翻译文件中使用config.yml中的全局变量吗? If yes, please can you give some example or useful link? 如果是,请提供一些示例或有用的链接吗?

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 (eg in your parameters.yml ): 覆盖translator.class参数(例如,在parameters.yml ):

translator.class:  Acme\YourBundle\Translation\Translator

Create the new Translator service: 创建新的Translator服务:

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

class Translator extends BaseTranslator
{

}

Finally override both trans and transChoice : 最后覆盖transtransChoice

/**
 * {@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)

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: 现在,您可以在模板中使用以下twig语法来获得预期的结果:

{{ 'I.love.website'|trans({'%website%': my_favorite_website}) }}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM