Misiur
Misiur

Reputation: 5297

Symfony 'trans' domain inside Twig template

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?

Upvotes: 29

Views: 34109

Answers (3)

cvsguimaraes
cvsguimaraes

Reputation: 13240

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) }}

Upvotes: 5

krishna
krishna

Reputation: 3647

You can also do using trans filter :

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

Upvotes: 73

Misiur
Misiur

Reputation: 5297

The solution is:

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

Upvotes: 30

Related Questions