jblond / twig-trans

Twig 3 翻译扩展

v1.1.0 2022-03-30 12:35 UTC

This package is auto-updated.

Last update: 2024-08-29 10:44:50 UTC


README

Latest Version Packagist Installs

简介

这是旧版 Twig 扩展 I18n / Intl / I18nExtension 的替代品,用于使用 po / mo gettext 文件进行翻译。

我不想安装 Symfony,只想安装 Twig。Symfony 似乎过于复杂。

此扩展使 Twig 模板能够再次使用 |trans{% trans %} + {% endtrans %}

安装

composer require jblond/twig-trans

使用示例

<?php

use jblond\TwigTrans\Translation;
use Twig\Environment;
use Twig\Loader\FilesystemLoader;
use Twig\TwigFilter;

require '../vendor/autoload.php';

$langCode = 'de_DE';
putenv("LC_ALL=$langCode.UTF-8");
if (setlocale(LC_ALL, "$langCode.UTF-8") === false) {
    echo sprintf('Language Code %s not found', $langCode);
}

// set the path to the translation
bindtextdomain("Web_Content", "./locale");

// choose Domain
textdomain("Web_Content");

$twigConfig = [
    'cache' => false,
    'debug' => true,
    'auto_reload' => true
];

$twigLoader = new FilesystemLoader('./tpl/');
$twig = new Environment($twigLoader, $twigConfig);
// if you need  {{ dump() }} in the twig templates add
//$twig->addExtension(new DebugExtension());
// and use Twig\Extension\DebugExtension;  // at the top of the file

// this is for the filter |trans
$filter = new TwigFilter(
    'trans', 
    function ($context, $string) {
        return Translation::transGetText($string, $context);
    }, 
    ['needs_context' => true]
);
$twig->addFilter($filter);

// load the i18n extension for using the translation tag for twig
// {% trans %}my string{% endtrans %}
$twig->addExtension(new Translation());

try {
    $tpl = $twig->load('default.twig');
} catch (Exception $exception) {
    echo $exception->getMessage();
    die();
}

// the array parameter (context) is optional for the render function
echo $tpl->render(['key1' => 'value1', 'key2' => 'value2']);

要求

  • PHP 7.2 或更高版本
  • PHP 多字节字符串 'gettext'
  • Twig >= 3.0

可选要求

  • xgettext 用于提取/生成 po 文件。

许可证(MIT 许可证)

查看 许可证

测试

composer run-script php_src
composer run-script php_test
composer run-script phpunit

贡献、愿望和错误

提出 问题