Symfony 'trans' domain inside Twig template

强颜欢笑 提交于 2021-02-06 09:41:05

问题


I'd like to do this:

$this->get('translator')->trans('notice.unregistered', array(), 'index');

Inside Twig template, so I don't have to pass this as an argument. How?


回答1:


You can also do using trans filter :

{{ 'translationkey'|trans({},'domain') }}



回答2:


The solution is:

{% trans from "domain" %}text{% endtrans %}



回答3:


You can add custom functions to change domains inside your templates.

Add your functions:

$getTextdomain = new Twig_SimpleFunction('get_textdomain', function () {
    return textdomain(NULL);
});
$setTextdomain = new Twig_SimpleFunction('set_textdomain', function ($domain) {
    textdomain($domain);
});

$twig->addFunction($getTextdomain);
$twig->addFunction($setTextdomain);

Then use it:

{% set originalDomain = get_textdomain() %}
{{ set_textdomain('errors') }}
{% trans "My error message" %}
{{ set_textdomain(originalDomain) }}


来源:https://stackoverflow.com/questions/7689644/symfony-trans-domain-inside-twig-template

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!