问题
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