29

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?

JasonMArcher
  • 14,195
  • 22
  • 56
  • 52
Misiur
  • 5,019
  • 8
  • 38
  • 54

3 Answers3

69

You can also do using trans filter :

{{ 'translationkey'|trans({},'domain') }}
krishna
  • 3,547
  • 5
  • 27
  • 29
  • it don't work when you re using it to translate strings from variables. – Max Małecki May 10 '12 at 13:25
  • 2
    Max you must be doing something wrong. This works for variables too (see: http://symfony.com/doc/current/book/translation.html#twig-templates e.g. `{{ message|trans({'%name%': 'Fabien'}, "app") }}`). – flu Jan 08 '13 at 10:30
  • well it's purpose is to work with variables, for string constants ``{% trans %}The value{% endtrans %}`` would be the way to go. – Adrian Föder Mar 16 '16 at 14:49
  • 1
    For concatenated expressions you'll have to set it up before the trans modifier: `{% set salutation = 'salutation.' ~ person.gender %} {{ salutation | trans({}, 'domain') }}` A direct `{{ 'salutation.' ~ person.gender | trans({}, 'domain') }}` doesn't work. – bibamann Jul 18 '19 at 15:27
  • This does NOT work for standalone Twig -- only for Symfony Twig. – Austin Burk Feb 20 '21 at 02:21
29

The solution is:

{% trans from "domain" %}text{% endtrans %}
Misiur
  • 5,019
  • 8
  • 38
  • 54
5

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) }}
cvsguimaraes
  • 12,910
  • 9
  • 49
  • 73