Reputation: 805
I want to add some HTML to Symfony 2 Translation. This way I will know which phrases in my application are translated and which not. I found in "Symfony\Component\Translation\Translator.php" function "trans". Now i want to add something in function return, for example "< /br>":
/**
* {@inheritdoc}
*
* @api
*/
public function trans($id, array $parameters = array(), $domain = null, $locale = null)
{
if (null === $locale) {
$locale = $this->getLocale();
} else {
$this->assertValidLocale($locale);
}
if (null === $domain) {
$domain = 'messages';
}
if (!isset($this->catalogues[$locale])) {
$this->loadCatalogue($locale);
}
return strtr($this->catalogues[$locale]->get((string) $id, $domain)."</br>", $parameters);
}
The issue is that when I run my application I'm getting for example "Tag< / b r>" (I have add spaces because in normal way it doesn't show here. HTML doesn't interprate this as HTML code but as a string. Is there any way to achieve what I want ? Maybe it is but in the other way ?
Upvotes: 2
Views: 1429
Reputation: 805
MY SOLUTION:
I have achieved what I wanted in few steps:
Override Translator.php and change translator.class in parameters.yml
public function trans($id, $parameters, $domain, $locale) { $return = parent::trans($id, $parameters, $domain, $locale); return "".$return.''); }
Set translation class in your css.
Set autoescape option to false in parameters.yml
twig: autoescape: false
Upvotes: 0
Reputation: 1715
I'll suggest you simply to use Markdown in your translation.
Then you can parse your translated message with a Markdown parser.
Example in Twig: 'my.message'|trans|markdown
(I suppose you have a Markdown filter, there is KnpMarkdownBundle)
Upvotes: 0
Reputation: 27190
This happens because you have the Twig Escaper extension active. That extension adds automatic output escaping to Twig, it defines the autoescape tag and the raw filter.
So I think the best option you got here is to define a new twig extension to let you translate your html strings without having to repeat myvar|raw
each time.
To see how it is possible to create a new Twig extension please check the docs here.
Use the same extension when escaping for JS and there should be no need to use anything else especially in your PHP controllers. That's because the escaping is done at the Twig level. Just remember to declare your new Twig filter as safe to avoid automatic escaping again:
$filter = new Twig_SimpleFilter('nl2br', 'nl2br', array('is_safe' => array('html')));
If you need to do some extra processing with the requested data so that you can track what strings are being requested and what not then just declare a new service as a proxy to the Symfony translation one. Your Twig extension can use the same service. This way you can converge all the requests to one single service.
Here a few useful links for you:
Upvotes: 1