fccn/webapp-tools-translate

一套用于在Web应用程序中启用翻译的工具

1.1.1 2018-10-11 13:46 UTC

This package is not auto-updated.

Last update: 2024-09-26 17:00:06 UTC


README

此工具集提供了一系列处理多语言和Web应用程序翻译的实用工具。它向Web应用程序添加了Gettext支持,并使用应用程序配置文件中定义的设置配置Gettext。它还支持文档翻译和完整HTML页面翻译。

本地化实用工具还提供了一种通过Makefile准备和启动xgettext的工具,并通过twig过滤器以及将twig模板解析为xgettext可理解的格式的实用工具与twig框架集成。

该项目还提供了一套Web组件,包括Slim框架:Locale服务、本地化中间件和语言切换控制器操作。

安装

您可以使用composer在项目中安装此集合

composer require fccn/webapp-tools-translate

为了完成安装,将localeutils文件夹的内容分别复制到[项目根目录]/locale[项目根目录]/utils。这些文件夹包含准备和启动xgettext以及解析twig文件的实用工具。

Locale文件夹

locale文件夹中的Makefile准备要由xgettex处理的文件内容,并调用xgettext生成.po和.mo文件。它配置在locale目录下工作。它在[项目根目录]/app文件夹中查找php代码,并在[项目根目录]/cache中查找解析的twig模板。

header.po文件是生成每种语言单独.po文件的基本文件。此文件必须位于locale文件夹中。

locale文件夹还包含翻译文件。每种语言都必须有自己的内容文件夹。文件夹必须使用国家ID命名(例如pt_PT)。每个语言文件夹必须具有以下结构

  • [国家ID]/
  • files/ - 文档翻译的位置
  • html/ - 完整HTML页面翻译的位置
  • LC_MESSAGES/ - Gettex翻译的位置

locale文件夹已包含预先构建的pt_PT和en_EN语言的文件夹。

Utils文件夹

如果您在Web应用程序中使用Twig,将需要在某个时刻从twig模板文件中提取模板字符串。不幸的是,xgettext实用工具本身不理解Twig模板。因此,[项目根目录]/utils/make_php_cache_files.php中的脚本将Twig模板转换为PHP文件,以便可以在这些文件上调用xgettext。该脚本需要Twig具有与您在Web应用程序中定义的相同的配置。您可以通过编辑[项目根目录]/utils/TwigConfigLoader.php文件来在make_php_cache_files.php脚本中加载所需的Twig扩展和过滤器。

配置

本地化实用工具是为了与FCCN的webapp骨架项目而设计的。因此,构建 po和mo文件的脚本将在[项目根目录]/app文件夹中搜索Web应用程序代码。如果您的应用程序代码存储在另一个位置,您需要在使用Gettext实用工具之前编辑[项目根目录]/locale/Makefile

本地化实用工具使用了来自Webapp Tools - common项目的站点配置加载器。以下键值对需要添加到应用程序配置文件$c数组中

$c = array(
    ...
    #----- locale configuration
    "defaultLocale"      => "pt_PT",          # Setup the default locale
    "defaultLocaleLabel" => "PT",             # and default locale label
    "locale_selection"   => "param",          # locale selection method, can be 'param' if locale to be set up by a url parameter, or 'cookie' if  locale is set up by cookie

    #- array of available locales
    "locales"            => array(
                              array("label" => "GB", "locale" => "en_GB", "flag_alt" => "English flag", "language" => "English"),
                              array("label" => "PT", "locale" => "pt_PT", "flag_alt" => "Portuguese flag", "language" => "Português"),
                              # add other languages here....
                              ),

    "locale_textdomain"  => "messages",
    "locale_path"        => "../locale", #path of the locale folder
    "locale_cookie_name" => "locale",    #name of the cookie to store locale information
    "locale_cookie_path" => "/",     #relative path of the locale cookie
    "locale_param_name" => "lang",    #name of the URL param to store locale information
    "request_attribute_name" => "locale", #name of the request attribute to store locale info

    #-twig parser configurations
    "twig_parser_templates_path" => "../templates",   #path for twig templates folder, can be an array if you are importing templates from other projects
    "twig_parser_cache_path" => "../cache",            #path for cache folder
    #activate verbose debug for debugging purposes (defaults to false)
    "verbose_debug" => false,
    ...
  )

twig解析器支持多个twig模板文件夹。您可以根据以下示例设置多个文件夹

$c = array(
    ...
    twig_parser_templates_path =>  array(
      0 => __DIR__ . '/../templates', //set the base template path
      //add other namespaces to twig, in the form of 'namespace' => 'path/to/twig/templates'
    ),
    ...
  );

在配置twig时,您需要将web应用程序使用的相同的twig扩展和过滤器加载到twig解析器中。这可以防止在解析twig模板时出现误解。为此,请编辑 [项目根目录]/utils/TwigConfigLoader.php 并将过滤器和扩展添加到 loadConfigs 函数中。

  public function loadConfigs($twig){
    ....

    #add the i18n extensions
    $twig->addExtension(new Twig_Extensions_some_extension());

    #add translate filter
    $filter = new Twig_SimpleFilter("my filter", function($stdClassObject) {
        return null;
    }),
    $twig->addFilter($filter);

    ...
  }

您还可以使用预置的配置加载器,例如在 src/TranslateConfigurationLoader.php 中定义的加载器。在 [项目根目录]/utils/TwigConfigLoader.php 中的 loadConfigs() 函数已加载以下一组用于本地化工具的过滤器和扩展。

  • Twig_Extensions_Extension_I18n - Twig国际化扩展
  • Twig_Extensions_Extension_Intl - Twig日期和时间本地化扩展
  • Translate过滤器

与Slim的集成

要启用对区域信息的全局访问,可以将Fccn\Lib\Locale的一个实例作为服务 - 区域服务 - 添加到您的Slim应用程序中。下面的示例显示了如何将服务添加到Slim容器中并在视图中创建一个全局的 lang 变量。

$app = new \Slim\App(...);

// Fetch DI Container
$container = $app->getContainer();

$container['locale'] = function ($cnt) {
    $locale = new Fccn\Lib\Locale();
    //add global lang var
    $cnt->view->getEnvironment()->addGlobal('lang', $locale);
    return $locale;
};

本地化工具提供了一种Slim中间件来将本地化添加到您的web应用程序中 - 本地化中间件。此中间件使用上面描述的区域服务。为了更好地集成,您需要配置区域以中间件集成。下面的示例显示了如何将本地化中间件添加到Slim应用程序中。

$app = new \Slim\App();

//get container
$container = $app->getContainer();

//Create the locale service

$container['locale'] = function ($cnt) {
    //set Locale to middleware integration
    $locale = new Fccn\Lib\Locale(array('slim_middleware' => true));
    //add global lang var
    $cnt->view->getEnvironment()->addGlobal('lang', $locale);
    return $locale;
};

//Add locale middleware
$app->add(new Fccn\WebComponents\LocaleMiddleware($container['locale']));

要切换语言,您可以使用语言切换器控制器操作。选择新语言的路径必须定义为 <站点URL>/<路径>/{lang},其中 lang 是在配置文件中定义的locale数组中的语言标签(不区分大小写)。例如,要定义路径 <站点URL>/utils/setlang/{lang} 的语言切换器控制器操作,其中 lang 是语言标签(不区分大小写),则

$app = new \Slim\App();

$app->get('/utils/setlang/{lang}', Fccn\WebComponents\SwitchLanguageAction::class);

添加更多语言

要创建额外的语言,请在 locale 文件夹内按以下操作执行。

  1. 添加一个带有国家ID的新目录。 mkdir -p es_ES/LC_MESSAGES
  2. 将头文件复制到目录中。 cp header.po es_ES/LC_MESSAGES/messages.po
  3. 创建目录以存放其他待翻译文件。 mkdir es_ES/files; mkdir es_ES/html
  4. 清理缓存。 make clean
  5. 更新消息文件。 make
  6. 编辑po文件并翻译它。 vi es_ES/LC_MESSAGES/messages.po
  7. 不要忘记分配语言,例如 "Language: es_ES\n"
  8. 更新消息文件。 make
  9. 编辑应用程序配置文件,将新语言添加到 locales 数组中。

用法

以下展示了语言工具的不同用法。

翻译HTML内容

将翻译的HTML片段放在 locale/[国家ID]/html/ 文件夹中。片段必须在所有语言文件夹中具有相同的名称。例如,要打印来自片段 locale/en_EN/html/my_snippet.html 的en_EN HTML内容,该片段的内容如下

<div class="col-md-12">
<p>This is a tranlated html snipped</p>
</div>

在设置区域为en_EN后,您应该这样做

  $locale = new \Fccn\Lib\Locale();
  $html_content = $locale->getHtmlContent('my_snippet');
  echo $html_content

这将转而打印出

<div class="col-md-12">
<p>This is a tranlated html snipped</p>
</div>

翻译文本内容

将翻译的片段放在 locale/[国家ID]/files/ 文件夹中。片段必须在所有语言文件夹中具有相同的名称。例如,要打印来自片段 locale/en_EN/files/my_snippet.txt 的en_EN内容,该片段的内容如下

This is a sample snippet of translated text

在将区域设置为en_EN后,您应该这样做

  $locale = new \Fccn\Lib\Locale();
  $text_content = $locale->getFileContent('my_snippet');
  echo $text_content

这将转而打印出

This is a sample snippet of translated text

翻译文本片段中可以包含变量。变量用括号{}表示(例如,{name})。例如,如果要让片段适应用户的姓名,您可以在 locale/en_EN/files/hello_user.txt 中定义片段的en_EN版本

Hello {user_name}.

要获取包含实例化变量的内容,在将区域设置为en_EN后,您应该这样做

  $locale = new \Fccn\Lib\Locale();
  $text_content = $locale->processFile('hello_user',array("{user_name}" => "New User"));
  echo $text_content

这将转而打印出

Hello New User

Gettext翻译

要在应用程序代码中添加可翻译内容,将想要翻译的内容写入 _() 内(例如 _('翻译我'))。

要在twig模板中添加可翻译内容,将提供的翻译过滤器加载到twig中。

 $twig = new Twig_Environment();
 \Fccn\Lib\TranslateConfigurationLoader::loadTwigConfigs($twig);

然后在twig模板中只需使用 trans 标签即可。

  <p>{% trans "Translatable content" %}</p>

每次您向应用程序和模板中添加内容时,都需要更新翻译。

  1. 转到 locale 目录并运行 make
  2. 这将更新个人语言目录中每个 LC_MESSAGES 目录下的 .po 文件,以包含新的内容。
  3. 编辑每种语言的 .po 文件并添加缺失的翻译。
  4. 再次在 locale 目录上运行 make,以更新 .mo 文件中的编译翻译。

要刷新翻译内容,请在 locale 目录上运行 make clean && make

测试

此项目使用 codeception 进行测试。要在项目文件夹的根目录下运行测试,请调用 composer test

贡献

请阅读 CONTRIBUTING.md 了解我们的行为准则以及向我们提交拉取请求的流程。

版本控制

我们使用 SemVer 进行版本控制。有关可用版本,请参阅此存储库的 标签

许可证

此项目使用 MIT 许可证 - 详细信息请参阅 LICENSE.md 文件。