I am looking for a working i18n example for Twig (the template engine).
Documentation is a bit sparse when it comes to language files. Where should they go, how should they look and what should they be named? I have been trying with .po/.mo files, no luck.
If someone could point me in the right direction...
See: the i18n extension example which does not really tell me much about the language files themselves.
Note: I want to use Twig on its own, not as part of Symfony.
Here is my php-file:
<?php
header('Content-Type: text/html; charset=utf-8');
$vars = array();
foreach($_POST as $key => $value) {
$vars[$key] = json_decode(utf8_encode(urldecode($value)));
}
/* Prepare Twig template enginge */
require_once './lib/Twig/Autoloader.php';
Twig_Autoloader::register();
$loader = new Twig_Loader_Filesystem('./templates');
$twig = new Twig_Environment($loader, array(
//'cache' => './cache',
'cache' => false
));
/* i18n */
$twig->addExtension(new Twig_Extensions_Extension_I18n());
$availableLanguages = array(
'en' => 'en_EN',
'de' => 'de_DE',
'default' => 'de_DE'
);
// Set language
$locale = array_key_exists($_GET['lang'], $availableLanguages) ? $availableLanguages[$_GET['lang']] : $availableLanguages['default'];
putenv('LC_ALL='.$locale);
setlocale(LC_ALL, $locale);
// Specify the location of the translation tables
bindtextdomain('kalkulator', 'includes/locale');
bind_textdomain_codeset('kalkulator', 'UTF-8');
// Choose domain
textdomain('kalkulator');
$template = $twig->loadTemplate('print.tpl');
$html = $template->render($vars);
switch($_GET['action']) {
case 'mail':
break;
default:
echo $html;
break;
}
?>
And inside includes/locale I have the following files:
-rw-r--r-- 1 user group 670 Jul 28 10:17 kalkulator-de_DE.mo
-rw-r--r-- 1 user group 982 Jul 28 10:22 kalkulator-de_DE.po
-rw-r--r-- 1 user group 688 Jul 28 10:38 kalkulator-en_EN.mo
-rw-r--r-- 1 user group 1004 Jul 28 10:38 kalkulator-en_EN.po
And inside the print.tpl file I am using tags to specify which parts are to be translated:
{% trans %}
Text to be translated
{% endtrans %}
The twig i18n extension is based on gettext. So first of all everything related to gettext applies. You find that documented here: Gettext Docs.
So now to the more concrete parts of you question, but please ensure you've at least understood the basic principles with gettext:
Into the directory that has been registered for the text-domain.
Language files should be named the following:
text-domain
-
locale.po/mo
Example for a text domain called
myAppPhp
and thefr_FR
locale:.po/.mo
sounds good to me, maybe you have just missed the path where to move them or you have forgotten to add the text-domain in front.I've tried everything possible in slim 3 but nothing was working, only slim 2, so I've created my own way. Basically the system detects the language from the browser and load the correct translation file, more details in the picture: