Twig translate phrase with tags inside

1.2k views Asked by At

Twig version - latest

Twig extensions version - latest


I want to avoid html-tags in .po files

Here is text with link inside phrase.

<p>{{ 'Click this <a href="/test/">test link</a>, friend' | trans | raw }}</p>

Using solution from this topic - https://stackoverflow.com/a/11546933/2145125

<p>{{ 'Click this %a_open%test link%a_close%, friend' | trans({'%a_open%' : '<a href="/test/">', '%a_close%' : '</a>'}) | raw }}</p>

Having PHP-warning Warning: gettext() expects exactly 1 parameter, 2 given

Compiled template PHP-code is

echo gettext("Click this %a_open%test link%a_close%, friend", array("%a_open%" => "<a href=\"/test/\">", "%a_close%" => "</a>"));

1

There are 1 answers

0
nokimaro On

Found 2 solutions.

trans + replace = gettext() + strtr() You can use named placeholders like %a_open% etc., order of placeholders doesn't matter

<p>{{ 'Click this %a_open% test link %a_close% friend' | trans | replace ({"%a_open%" : '<a href="/test/">', "%a_close%" : "</a>"}) | raw }}</p>

trans + format = gettext() + spritf

<p>{{ 'Click this %stest link%s, friend' | trans | format('<a href="/test/">', '</a>') | raw }}</p>