本教程演示了如何使用Twig和GetText向PHP应用程序添加多语言支持。 它比Symfony的翻译组件(例如Symfony的翻译组件)要快得多。我们将修改既有英语应用程序(NOFW)来说明这一点。
键优点:
xgettext
和.po
文件生成,通过.mo
扩展的twig集成以及有用的实用程序脚本。i18n
设置和基础知识:
我们将使用宅基地改进(假设已经安装了GetText;稍后提供手动安装的说明)。 因为NOFW使用树枝,因此需要扩展:>
i18n
git clone https://github.com/swader/nofw cd nofw git checkout tags/2.93 -b 2.93 composer require twig/extensions
>按照NOFW读取文件进行配置数据库。 该应用程序现在应该运行。
getText使用
或其别名标记可翻译字符串。 如果找不到翻译,则返回原始字符串(占位符)。
:gettext("string")
_("string")
i18n.php
<?php $language = "en_US.UTF-8"; putenv("LANGUAGE=" . $language); setlocale(LC_ALL, $language); $domain = "messages"; bindtextdomain($domain, "Locale"); bind_textdomain_codeset($domain, 'UTF-8'); textdomain($domain); echo _("HELLO_WORLD");
代码为GetText设置语言,语言环境和域。 由于缺少语言文件,因此运行此功能会回荡“ Hello_world”。
> 字符串提取:
>使用
从您的文件中提取字符串:这将创建
(便携式对象模板)。 生成一个英语文件:xgettext
xgettext --from-code=UTF-8 -o Locale/messages.pot public/i18n.php
,翻译“ hello_world”(例如,“ howdy”)。 编译为messages.pot
:.po
msginit --locale=en_US --output-file=Locale/en_US/LC_MESSAGES/messages.po --input=Locale/messages.pot
>添加一种新语言(例如,克罗地亚语): twig Integration:
:
更新>使用
奖励:实用程序脚本(App/bin/i18n): ,,, >和
和 以上是带有getText的简单多语言树枝应用程序的详细内容。更多信息请关注PHP中文网其他相关文章!.mo
>
sudo locale-gen hr_HR hr_HR.UTF-8; sudo update-locale; sudo dpkg-reconfigure locales
.po
> file:mkdir -p Locale/hr_HR/LC_MESSAGES; msginit --locale=hr_HR --output-file=Locale/hr_HR/LC_MESSAGES/messages.po --input=Locale/messages.pot
messages.po
>中将“ hello_world”转换为“ zdravo”。
.mo
<>msgfmt -c -o Locale/hr_HR/LC_MESSAGES/messages.mo Locale/hr_HR/LC_MESSAGES/messages.po
i18n.php
和测试。 可能需要重新启动服务器。hr_HR.UTF-8
app/config/config_web.php
git clone https://github.com/swader/nofw
cd nofw
git checkout tags/2.93 -b 2.93
composer require twig/extensions
trans
<?php
$language = "en_US.UTF-8";
putenv("LANGUAGE=" . $language);
setlocale(LC_ALL, $language);
$domain = "messages";
bindtextdomain($domain, "Locale");
bind_textdomain_codeset($domain, 'UTF-8');
textdomain($domain);
echo _("HELLO_WORLD");
xgettext
app/bin/twigcache.php
然后从缓存的文件中提取字符串:xgettext --from-code=UTF-8 -o Locale/messages.pot public/i18n.php
msginit --locale=en_US --output-file=Locale/en_US/LC_MESSAGES/messages.po --input=Locale/messages.pot
.po
msgmerge
.mo
addlang.sh
>> files。 这些脚本在原始文本中详细介绍。update-pot.sh
>
update-mo.sh
config.sh
部署:.pot
.mo
msgfmt -c -o Locale/en_US/LC_MESSAGES/messages.mo Locale/en_US/LC_MESSAGES/messages.po