|
| 1 | +# Twig Trans |
| 2 | + |
| 3 | +[](https://github.com/JBlond/twig-trans/releases) |
| 4 | + |
| 5 | +## Introduction |
| 6 | + |
| 7 | +This is the replacement for the old **Twig** Extensions **I18n** / **Intl** for the translation with po / mo |
| 8 | +**gettext** files. |
| 9 | + |
| 10 | +I didn't wanted to Symfony, but Twig only. Symfony seemed to be too much overhead. |
| 11 | + |
| 12 | +This extension enable Twig templates to use `|trans` and `{% trans %}` + `{% endtrans %}` again |
| 13 | + |
| 14 | +## Install |
| 15 | + |
| 16 | +```shell |
| 17 | +composer require jblond/twig-trans |
| 18 | +``` |
| 19 | + |
| 20 | +## Example Use |
| 21 | + |
| 22 | +```PHP |
| 23 | +<?php |
| 24 | + |
| 25 | +use jblond\TwigTrans\Translation; |
| 26 | +use Twig\Environment; |
| 27 | +use Twig\Loader\FilesystemLoader; |
| 28 | +use Twig\TwigFilter; |
| 29 | + |
| 30 | +require '../vendor/autoload.php'; |
| 31 | + |
| 32 | +$langCode = 'de_DE'; |
| 33 | +putenv("LC_ALL=$langCode.UTF-8"); |
| 34 | +if (setlocale(LC_ALL, "$langCode.UTF-8") === false) { |
| 35 | + sprintf('Language Code %s not found', $langCode); |
| 36 | +} |
| 37 | + |
| 38 | +// set the path to the translation |
| 39 | +bindtextdomain("Web_Content", "./locale"); |
| 40 | + |
| 41 | +// choose Domain |
| 42 | +textdomain("Web_Content"); |
| 43 | + |
| 44 | +$twigConfig = array( |
| 45 | + 'cache' => false, |
| 46 | + 'debug' => true, |
| 47 | + 'auto_reload' => true |
| 48 | +); |
| 49 | + |
| 50 | +$twigLoader = new FilesystemLoader('./tpl/'); |
| 51 | +$twig = new Environment($twigLoader, $twigConfig); |
| 52 | + |
| 53 | +// this is for the filter |trans |
| 54 | +$filter = new TwigFilter('trans', function (Environment $env, $context, $string) { |
| 55 | + return Translation::TransGetText($string, $context); |
| 56 | +}, ['needs_context' => true, 'needs_environment' => true]); |
| 57 | + |
| 58 | +// load the i18n extension for using the translation tag for twig |
| 59 | +// {% trans %}my string{% endtrans %} |
| 60 | +$twig->addFilter($filter); |
| 61 | +$twig->addExtension(new Translation()); |
| 62 | + |
| 63 | +try { |
| 64 | + $tpl = $twig->load('default.twig'); |
| 65 | +} catch (Exception $exception) { |
| 66 | + echo $exception->getMessage(); |
| 67 | + return; |
| 68 | +} |
| 69 | + |
| 70 | +$tpl->render(); |
| 71 | +``` |
| 72 | + |
| 73 | + |
| 74 | +## Requirements |
| 75 | + |
| 76 | +* PHP 7.2 or greater |
| 77 | +* PHP Multibyte String |
| 78 | +' gettext' |
| 79 | + |
| 80 | + |
| 81 | +### License (MIT License) |
| 82 | + |
| 83 | +see [License](LICENSE) |
| 84 | + |
| 85 | +## Tests |
| 86 | + |
| 87 | +```bash |
| 88 | +composer run-script php_src |
| 89 | +``` |
0 commit comments