I've managed to successfully enable internationalization and {% trans %} tag in twig using these lines:
$language = "...";
$domain = "project";
putenv("LC_MESSAGES=$language");
setlocale(LC_MESSAGES, $language);
bindtextdomain($domain, SITE_DIR . "locale");
textdomain($domain);
bind_textdomain_codeset($domain, "UTF-8");
And twig template:
...
{% trans "Translation.Key" %}
...
Unfortunately it works randomly. I mean, while I keep pressing F5, say, every second, or going between pages, sometimes it switches to the translated string as it should ("Translation.Key" becomes "Localized value to output"), and sometimes it falls back to outputting the string under {% trans %} tag ("Translation.Key").
Meanwhile I can't see any errors in my logs. What should I check to understand the source of the problem and to get it to work consistently?
Thanks in advance.
In my case the problem is solved by restarting Apache (or php5-fpm when I use nginx on remote server) every time I make changes to the translations files. Otherwise, gettext works glitchy as described in the question.
Personally, it came from php-fpm. Restarting Apache did nothing.
To restart php-fpm on centos7:
For other OS, please check this link to restart php-fpm: https://serverfault.com/questions/189940/how-do-you-restart-php-fpm
Make sure your Twig Cache is disabled during development.