I am trying to have my twig templates translated using the Symfony Translator Component and .mo files. I used the i18n extention before but wanted a more reliable approach since locale handling for translations on Windows is a nightmare.
These class functions prepare the translation and template:
/**
* Constructor.
*
* @param string $template_dir
* @param string $locale
* @param string $locale_path
*/
public function __construct($template_dir, $locale, $locale_path)
{
$loader = new Twig_Loader_Filesystem($template_dir);
$this->parser = new TemplateNameParser();
$this->template = new \Twig_Environment($loader);
$this->translator = new Translator($locale);
$this->translator->addLoader('mo', new \Symfony\Component\Translation\Loader\MoFileLoader());
$this->translator->addResource('mo', $locale_path, $locale);
$this->template->addExtension(new TranslationExtension($this->translator));
}
/**
* Render template.
*/
public function render($name,$parameters=[]) {
return $this->template->loadTemplate($name,$parameters)->render();
}
Then i have this template:
<h1>{% trans 'Hello World!' %}</h1>
which throws this error:
Uncaught Twig_Error_Syntax: Unexpected token. Twig was looking for the "with", "from", or "into" keyword.
Which i get because i am not adding the Twig_Extensions_Extension_I18n extension to twig environment. If i do that, the texts in trans functions are not translated because i am not using the filter as i should. For it to work i need to use the trans filter like so: {{ 'Some text'|trans }}
.
Is there a way to make translation work with {% trans 'Some text' %}
instead of {{ 'Some text'|trans }}
? For example, can i add a custom trans function somewhere in the chain?
Note: I know that {% trans %}Some text{% endtrans %}
works, but all my templates already use this syntax {% trans 'Some text' %}
, and i would like to prevent having to rewrite everything.
{% trans('Hello World!') %}
if it's a function? – Arend{% trans 'Some text' %}
. – Yolo{% trans %}'Some text'{% endtrans %}
, would that solve your problem? – Arend{% trans %}Some text{% endtrans %}
works. But i will have to alter all 200 templates to use that syntax. I would like to prevent that. I will add a comment to my question to include this. – Yolo{% trans 'lalal translate this' %}
syntax? Is this an older syntax, or from a different extension? – Arend