cooperaj / better-twig-i18n
提供基于gettext语言文件的i18n功能。
Requires
- php: ^8.1.0
- ext-gettext: *
- gettext/gettext: ^5.5
- gettext/translator: ^1.0
- nikic/php-parser: ^4.9
- symfony/finder: ^4.0 || ^5.0
- twig/twig: ^v3.0
Requires (Dev)
- mikey179/vfsstream: ^v1.6
README
允许使用与当前官方Twig翻译扩展相同的语法,在Twig中使用POT/PO/MO(gettext)语言定义集。
它支持从gettext/gettext库完全提取Twig模板到语言目录中,如果您需要,可以用来编写POT文件。
此外,支持从PHP直接使用\Acpr\I18n\Translator
中的translate
函数提取文本值。例如,您可能正在创建翻译后的闪存消息并将它们存储在会话中,以便后续的Twig模板使用。
支持
Twig
-
翻译标签(
{% trans %} ... {% endtrans %}
)和过滤器(| trans
) -
变量插值
{% trans with { '%var%': var } %}%var%{% endtrans %}
-
复数
{% trans count 3 %}%count% item|%count% items{% endtrans %}
-
特定领域的消息
{% trans from 'errors' %} ... {% endtrans %}
-
消息上下文
{% trans %} ... {% context %}Some context{% endtrans %}
-
翻译的注释/备注
{% trans %} ... {% notes %}A translation note{% endtrans %}
-
或者所有这些的组合
{% trans count 5 with { '%name%': 'Adam' } from 'errors' %} %name% has %count% apple|%name% has %count% apples {% notes %}A translation note {% context %}Some context to the translation {% endtrans %}
提取的结果将是一个包含以下内容的
errors.pot
文件#. A translation note msgctxt "Some context to the translation" msgid "%name% has %count% apple" msgid_plural "%name% has %count% apples" msgstr[0] ""
其(默认,即未提供语言)输出将如下所示
Adam has 5 apples
PHP
PHP提取是通过通过nikic/php-parser解析您的PHP文件来工作的。这要求您的PHP是有效的才能工作。
您可能有一个PHP文件
/** @var $translator \Acpr\I18n\Translator **/ $pluralApples = $translator->translate( '%name% has %count% apple', [ '%name' => 'Adam' ], 'errors', 'Some context to the translation', '%name% has %count% apples', 5 ); // Assuming no translations had been loaded // $pluralApples == 'Adam has 5 apples'
提取的结果将是一个包含以下内容的errors.pot
文件
msgctxt "Some context to the translation"
msgid "%name% has %count% apple"
msgid_plural "%name% has %count% apples"
msgstr[0] ""
限制
-
提取特别寻找具有正确签名的
translate
函数的使用。这可能会导致依赖于您的代码库的假阳性。 -
目前无法将注释/备注添加到翻译条目中。
-
为了正确解析值,
translate
函数的字符串参数必须内联字符串(引号或heredoc)。无法使用变量。// This will *not* work $var = 'I have an apple'; $value = $translator->translate($var); // This will $value = $translator->translate('I have an apple');
用法
请参阅extract.php和index.php以获取示例用法。
升级
从先前版本升级到v3.0.0
v3引入了一种新的提取键的方法,该方法从主要语言键中删除超过2个字符的空白(查看发行说明以获取更多信息)
在脚本文件夹中有一个可用的脚本,它将帮助将您现有的任何PO文件迁移到较新的键,并最小化poedit决定所有内容都是新的而不是不同的痛苦。它可能需要根据您的需求进行编辑,但使用很简单。
$ cp scripts/v3_po_update.php folder/containing/po.files $ cd folder/containing/po.files # edit script as appropriate for your translation domains $ php v3_po_update.php