集成

In-context Editor (Strings)

文本由 Phrase Language AI 从英语机器翻译而得。

可用于

  • Team、Professional、Business、Enterprise 和 Software UI/UX 计划

关于许可问题,请联系销售团队

包含在

  • Advanced 和 Enterprise 套餐(原)

关于许可问题,请联系销售团队

In-context Editor 旨在帮助译员更高效地完成工作,并通过与 Strings 翻译编辑器 的直接集成来翻译网页。

目前有两个版本可用:

  1. In-context Editor

    包含新功能(多语言视图、布局选项、批量操作、协作功能等)以及来自翻译编辑器的 UI。

  2. 旧版 In-context Editor

安装 In-context Editor 后,可以对其进行自定义以适配多种技术。

安装 Strings In-context Editor

要求

要使用 In-context Editor,应用程序需要:

  • 基于 Web 的网站、Web 应用程序、移动站点等。

  • 译员可以访问运行编辑器所在的 Web 服务器。如果需要,这可以是一个本地环境。

  • 键值本地化文件结构。

    提取了可译的 Strings 的网站,以及使用键值结构来呈现翻译的视图层。

  • 暴露给视图或模板层的键名。

  • 呈现编辑器的 JavaScript 代码片段。

  • 理想情况下,应有一个专门的翻译环境。这可以是预演环境的复制,虽然最初设置的工作量较大,但能提供更好的工作流和更高的稳定性。

    如果无法使用专用环境,可以使用现有的预发布环境,并根据需要选择启用 In-context Editor。

JavaScript 代码片段

在应用程序布局中包含 JavaScript 代码片段。

该代码片段包含以下所需代码:

Project ID 位于项目设置中。

Account ID 位于 Strings 公司设置中。

示例:

<script type="text/javascript">
    window.PHRASEAPP_CONFIG={ // Do not change this name for the config to work
      accountId: 'ACCOUNT_ID',
      projectId: 'PROJECT_ID',
      datacenter: 'eu', // Set to 'us' for US data center
      prefix: '{{__', // Set to the prefix for the key format in the view templates
      suffix: '__}}', // Set to the suffix for the key format in the view templates
      disableShortcuts: false, // Set to true to disable keyboard shortcuts
      autoLowercase: true, // Set to false if keys contain capital letters
    };
  </script>
  <script type=\"module\" async=\"\" src=\"https://cdn.phrase.com/strings/plugins/editor/latest/ice/index.js\"></script>

Web 框架安装

i18next

注释

i18next Phrase In-context Editor Post Processor 支持所有高于 19.5.1 的 i18next 版本。尽管此库也可能适用于以前的版本,但它们不受官方支持,并且可能不会获得任何特定的更新或错误修复。

要在该环境中安装 In-context Editor,请按照以下步骤操作:

  1. 使用首选的包管理器安装 i18next-phrase-in-context-editor-post-processor 库:

    # yarn
    yarn add i18next-phrase-in-context-editor-post-processor
    
    # npm
    npm install i18next-phrase-in-context-editor-post-processor

    注释

    推荐的库版本为 1.4.0 或更高版本。

    或通过 CDN 加载:

    <script src="https://unpkg.com/i18next-phrase-in-context-editor-post-processor"></script>
  2. Bootstrap(示例):

    import i18next from 'i18next';
    import i18nextXHRBackend from 'i18next-xhr-backend';
    
    i18next
        .use(i18nextXHRBackend)
        .init({
            fallbackLng: 'en',
            debug: true,
            ns: ['special', 'common'],
            defaultNS: 'special',
            backend: {
                // load some translations from i18next-gitbook repo
                loadPath: 'https://raw.githubusercontent.com/i18next/i18next-gitbook/master/locales/{{lng}}/{{ns}}.json',
                crossDomain: true
            }
        }, function(err, t) {
            // do something on i18next initialization
        });

    要集成该库:

    1. i18next-phrase-in-context-editor-post-processor 库中导入 PhraseInContextEditorPostProcessor

    2. 创建新的 i18next Phrase In-Context Editor Post Processor 实例,并将 PhraseConfig 作为参数传递。

    3. 将新创建的 i18next Phrase In-Context Editor Post Processor 实例传递给 i18next use 方法。

    4. phraseInContextEditor 字符串添加到 postProcess 数组属性(在 i18next init 方法的配置对象中传递)。

  3. 在设置中将 ICE JavaScript 代码片段添加到 i18next 实例。

    示例代码片段:

    i18nextInstance.use(new PhraseInContextEditorPostProcessor({
          phraseEnabled: true,
          projectId: '00000000000000004158e0858d2fa45c',
          accountId: '0bed59e5',
        }))

    注释

    必须提供 accountId 才能成功设置 ICE。账户 ID 位于 Strings 公司设置中。

    如果需要,配置 useOldICE 属性以切换到 old ICE

    i18nextInstance.use(new PhraseInContextEditorPostProcessor({
          phraseEnabled: true,
          projectId: '00000000000000004158e0858d2fa45c',
          accountId: '0bed59e5',
          useOldICE: true,
        }))
  4. 启动 In-context Editor。

  5. 在网页浏览器中打开应用程序以显示 In-context Editor。使用任何 Phrase 公司用户登录。

配置选项和示例方法

Vue I18n

注释

Vue I18n Phrase In-context Editor 支持所有 8.17.5 及更高版本的 Vue I18n。此库可能适用于以前的版本,但它们不受官方支持,也不会获得任何特定的更新或错误修复。

要在该环境中安装 In-context Editor,请按照以下步骤操作:

  1. 使用首选包管理器安装 newest package

    # yarn
    yarn add vue-i18n-phrase-in-context-editor
    
    # npm
    npm install vue-i18n-phrase-in-context-editor

    或通过 CDN 加载(手动注册 window['vue-i18n-phrase-in-context-editor']):

    <script src="https://unpkg.com/vue-i18n-phrase-in-context-editor/dist/vue-i18n-phrase-in-context-editor.umd.min.js"></script>
    
  2. Bootstrap(示例):

    import Vue from 'vue';
    import VueI18n from 'vue-i18n';
    
    Vue.use(VueI18n);
    
    const i18n = new VueI18n({
      locale: process.env.VUE_APP_I18N_LOCALE || 'en',
      fallbackLocale: process.env.VUE_APP_I18N_FALLBACK_LOCALE || 'en',
      messages: {
          hello: 'Hello world!'
      }
    });
    
    new Vue({
      i18n,
      render: h => h(App)
    }).$mount('#app');

    要集成该库:

    1. 导入 Vue I18n Phrase In-context Editor 库。

    2. 创建新的 Vue I18n Phrase In-context Editor 实例,将 Vue I18n 实例作为第一个参数传递,将 Phrase Config 作为第二个参数传递。

配置选项和示例方法

React (intl)

注释

此库可能无法在 IE11 或更旧的浏览器中 工作。如果需要支持更旧的浏览器,请将 Babel 添加 到构建流水线中。

此库继承了 react-intl 包的通用组件。如果通过调用 initializePhraseAppEditor 启用了 Phrase,组件的行为将会 更改。

要在该环境中安装 In-context Editor,请遵循以下步骤:

  1. 通过 NPM 安装 最新包

    npm install react-intl-phraseapp

    或从 原文/源语 构建:

    npm run dist
    npm install
  2. 配置:

    let config = {
      projectId: '<YOUR_PROJECT_ID>',
      accountId: '<YOUR_ACCOUNT_ID>',
      phraseEnabled: true,
      prefix: "[[__",
      suffix: "__]]",
      fullReparse: true
    };

    项目的 项目 ID 可在 项目 设置中找到。

    账户 ID 可在 Strings 公司 设置中找到。

  3. 将代码片段添加到 react 应用中:

    import {initializePhraseAppEditor} from 'react-intl-phraseapp'
    
    let config = {
      projectId: '<YOUR_PROJECT_ID>',
      accountId: '<YOUR_ACCOUNT_ID>',
      phraseEnabled: true,
      prefix: "[[__",
      suffix: "__]]",
      fullReparse: true
    };
    
    initializePhraseAppEditor(config);
  4. 查找 FormattedMessage 的所有导入,并将 原文/源语 从 react-intl 更改为 react-intl-phraseapp

    import {FormattedMessage} from 'react-intl-phraseapp'
  5. 使用 jest 运行单元测试:

    npm test
代码示例

演示 展示了 Phrase In-context Editor 与 react-intl 的 集成。

Angular 2 (ngx-translate)

先决条件
  • 注册 Phrase Strings 账户。

  • 使用 ngx-translate 模块进行 Angular 2 应用程序的本地化。

要在该环境中安装 In-context Editor,请遵循以下步骤:

  1. 使用 NPM 安装:

    npm install ngx-translate-phraseapp
  2. 配置:

    import { initializePhraseAppEditor, PhraseConfig } from 'ngx-translate-phraseapp';
    
    let config: PhraseConfig = {
      projectId: '<YOUR_PROJECT_ID>',
      accountID: '<YOUR_ACCOUNT_ID>'
      phraseEnabled: true,
    };

    项目的 项目 ID 可在 项目 设置中找到。

    账户 ID 可在 Strings 公司 设置中找到。

    如果需要,配置 useOldICE 属性以切换到 old ICE

    let config = {
      projectId: '<YOUR_PROJECT_ID>',
      accountID: '<YOUR_ACCOUNT_ID>',
      phraseEnabled: true,
      useOldICE: true,
    };
    
    initializePhraseAppEditor(config);

    如果需要,添加美国特定 URL 以启用通过美国 数据中心 工作:

    baseUrl: "https://us.app.phrase.com",
    apiBaseUrl: 'https://api.us.app.phrase.com/api/v2',
    oauthEndpointUrl: "https://api.us.app.phrase.com/api/v2/authorizations",
    profileUrl: "https://us.app.phrase.com/settings/profile",
  3. 默认情况下,编辑器文档解析器会将所有键转换为小写。如果遇到此行为的问题并希望在编辑器中使用区分大小写的键,请禁用自动小写功能:

    let config = {
      // ...
      autoLowercase: false
    }
  4. 将这些代码片段添加到 Angular 应用程序中:

    app.component.ts

    import { initializePhraseAppEditor, PhraseAppCompiler, PhraseConfig} from 'ngx-translate-phraseapp'
    
    let config: PhraseConfig = {
      projectId: '<YOUR_PROJECT_ID>',
      accountID: '<YOUR_ACCOUNT_ID>'
      phraseEnabled: true,
    };
    
    initializePhraseAppEditor(config);

    app.module.ts

    import { TranslateModule, TranslateLoader, TranslateCompiler } from '@ngx-translate/core';
    import { HttpClientModule, HttpClient } from '@angular/common/http';
    import { PhraseAppCompiler } from 'ngx-translate-phraseapp'
    import { AppComponent } from './app.component';
    
    
    export function HttpLoaderFactory(http: HttpClient) {
      return new TranslateHttpLoader(http);
    }
    
    @NgModule({
      declarations: [
        AppComponent
      ],
      imports: [
        BrowserModule,
        HttpClientModule,
        TranslateModule.forRoot({
          loader: {
            provide: TranslateLoader,
            useFactory: HttpLoaderFactory,
            deps: [HttpClient]
          },
          compiler: {
            provide: TranslateCompiler,
            useClass: PhraseAppCompiler
          }
        }),
      ],
      providers: [],
      bootstrap: [AppComponent]
    })
代码示例

demo app 展示了 In-context Editor 与 Angular 和 ngx-translate 的集成。

Ruby on Rails (i18n)

注释

此库可能无法在旧版浏览器或 Microsoft IE11 中直接工作。如果需要支持这些浏览器,请将 Babel 添加到构建流水线中。

先决条件

  • 注册 Phrase Strings 账户。

  • 使用 Rails 也使用的优秀 i18n gem。

要在该环境中安装 In-context Editor,请遵循以下步骤:

  1. 使用以下方法之一将 phraseapp-in-context-editor-ruby 库添加到所需环境:

    • 通过 Gem

      gem install phraseapp-in-context-editor-ruby
    • 通过 Bundler

      将其添加到 Gemfile

      gem 'phraseapp-in-context-editor-ruby
    • 直接从 原文/源语 构建以获取最新最棒的功能:

      bundle && gem build
  2. 通过执行 Rails 生成器来 创建 初始化程序文件:

    rails generate phraseapp_in_context_editor:install --account_id=<YOUR_ACCOUNT_ID> --project-id=<YOUR_PROJECT_ID>

    项目的 项目 ID 可在 项目 设置中找到。

    账户 ID 可在 Strings 公司 设置中找到。

  3. 将 Ruby 代码片段添加到应用程序布局 app/views//layouts/application.html.erb

    <%= load_in_context_editor %>
  4. 将以下配置添加到初始化程序 /config/initializers/phraseapp_in_context_editor.rb

      config.enabled = true
      config.project_id = "YOUR_PROJECT_ID"
      config.account_id = "YOUR_ACCOUNT_ID"
      config.datacenter = "eu"

    如果需要,设置美国 数据中心 以 启用 与美国端点的协作:

      config.enabled = true
      config.project_id = "YOUR_PROJECT_ID"
      config.account_id = "YOUR_ACCOUNT_ID"
      config.datacenter = "us"
  5. 在任何 Web 浏览器中打开应用程序,即可看到应用于该应用的 In-context Editor。使用任何 Phrase 公司用户登录。

代码示例

demo 展示了 Phrase In-context Editor 与 react-i18next 的 集成。

Django

先决条件

  • 注册 Phrase Strings 账户。

  • 使用 Python 的 Django 框架。

注释

ICE 的旧版本自 2.0.0 版本起不再可用。

要在该环境中安装 In-context Editor,请遵循以下步骤:

  1. 使用 pip 安装 django-phrase 包:

    $ pip install django-phrase
  2. 将 Phrase 添加到已安装应用列表:

    INSTALLED_APPS = (
    
        'phrase',
    
    )
  3. 将以下模板片段添加到布局文件 templates/base_generic.html 或同等文件中:

    {% load phrase_i18n %}
    {% phrase_javascript %}
  4. 在模板中使用 phrase_i18n 模板标签(例如,demo/ice_demo/templates/index.html):

    {% load phrase_i18n %}
  5. 将以下配置添加到 settings.py

        # Phrase In-Context Editor settings
        PHRASE_ENABLED = True
        PHRASE_ACCOUNT_ID = "YOUR_ACCOUNT_ID"  # Set your own account id
        PHRASE_PROJECT_ID = "YOUR_PROJECT_ID"  # Set your own project id
        PHRASE_DATACENTER = "eu"  # Choose your datacenter 'eu' | 'us'
        PHRASE_PREFIX = "{{__"
        PHRASE_SUFFIX = "__}}"

    项目的 项目 ID 可在 项目 设置中找到。

    账户 ID 可在 Strings 公司 设置中找到。

    如果出现问题,可以手动集成 JavaScript snippet

  6. 在任何 Web 浏览器中打开应用程序,即可看到应用于该应用的 In-context Editor。使用任何 Phrase 公司用户登录。

GitHub 上的 Django 适配器代码

代码示例

demo 应用程序演示了如何将 In-context Editor 与 Django 应用程序集成。

Flask

先决条件

  • 注册 Phrase Strings 账户。

  • 使用 Flask 框架进行 Python 开发。

注释

ICE 的旧版本自 2.0.0 版本起不再可用。

要在该环境中安装 In-context Editor,请遵循以下步骤:

  1. 使用 pip 安装 Flask-Phrase 软件包:

    pip install Flask-Phrase
  2. 将以下配置添加到 Flask 应用程序(app.configconfig.py)中:

    PHRASEAPP_ENABLED = True
    PHRASEAPP_PREFIX = '{{__'
    PHRASEAPP_SUFFIX = '__}}'

    应用程序代码应如下所示:

    from flask import Flask, [...]
    from flask_babel import Babel
    from flask_phrase import Phrase, gettext, ngettext
    app = Flask(__name__)
    babel = Babel(app)
    phrase = Phrase(app)
  3. 将 Phrase JavaScript 代码片段 添加到基础布局文件中的以下标签内(它应位于模板文件的部分内):

    <script>
        window.PHRASEAPP_CONFIG = {
            projectId: "YOUR-PROJECT-ID",
            accountId: "YOUR-ACCOUNT-ID",
            datacenter: "eu",
        };
        (function() {
            var phrasejs = document.createElement('script');
            phrasejs.type = 'module';
            phrasejs.async = true;
            phrasejs.src = 'https://cdn.phrase.com/latest/ice/index.js'
            var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(phrasejs, s);
        })();
    </script>

    项目的 项目 ID 可在 项目 设置中找到。

    账户 ID 可在 Strings 公司 设置中找到。

    如果需要,设置美国 数据中心 以 启用 与美国端点的协作:

    window.PHRASEAPP_CONFIG = {
        projectId: "YOUR-PROJECT-ID",
        accountId: "YOUR-ACCOUNT-ID",
        datacenter: "us",
    };

PHRASEAPP_ENABLED = True 时,该软件包会修改翻译函数的返回值,以呈现 In-context Editor 可以读取的格式。当设置为 False 时,它将回退到标准的 Flask-Babel's gettext 函数。

代码示例

演示 应用程序展示了如何将 In-context Editor 与 Flask 应用程序集成。

Symfony 5.x

先决条件

  • 注册 Phrase Strings 账户。

  • 使用 Symfony 框架进行 PHP 开发。

注释

2.0.0 版本支持 Symfony 5 及更高版本。如果使用 Symfony 2、3 或 4,请查看 旧版本 的 In-context Editor。

要将 In-context Editor 与 Symfony 应用程序集成,请按照以下步骤操作:

  1. PhraseStringsInContextEditor 及其内容复制到存储库的 /src/Service 文件夹或所需位置。如果放置在其他位置,请相应地调整命名空间。

  2. 调整 config/services.yaml 以使用 Phrase 的适配器装饰 译员 服务:

    services:
        ...
        App\Service\PhraseStringsInContextEditor\Translator:
            decorates: translator
  3. 将以下 JavaScript 代码片段添加到基础或 Twig 布局模板的 {% block javascripts %} 之间,以便 In-context Editor 可以读取网页:

    <script>
        window.PHRASEAPP_CONFIG = {
            accountId: '0bed59e5',
            projectId: '00000000000000004158e0858d2fa45c',
            datacenter: 'eu',
            origin: 'phrase-symfony',
        };
        (function() {
            var phrasejs = document.createElement('script');
            phrasejs.type = 'module';
            phrasejs.async = true;
            phrasejs.src = 'https://cdn.phrase.com/latest/ice/index.js'
            var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(phrasejs, s);
        })();
    </script>

    Symfony 应用程序现已连接到 In-context Editor。

    项目的 项目 ID 可在 项目 设置中找到。

    账户 ID 可在 Strings 公司 设置中找到。

    如果需要,设置美国 数据中心 以 启用 与美国端点的协作:

    window.PHRASEAPP_CONFIG = {
        projectId: "YOUR-PROJECT-ID",
        accountId: "YOUR-ACCOUNT-ID",
        datacenter: "us",
    };
  4. 重新加载应用程序并使用 Phrase 凭据登录,以直接在网页上开始翻译流程。

代码示例

demo 应用程序演示了如何将 In-context Editor 与 Symfony 应用程序集成。

设置 In-context Editor

显示键名称

通常,视图层通过将可译的字符串名称(即键)传递给某种翻译方法或视图辅助程序来渲染翻译。

PHP 代码示例:

$translations = array(

  "page.headline" => "Some Headline",

  "page.link.label" => "I am a link",

  "page.link.hint" => "Click me"

)

function translate($keyName) {

  return $translations[$keyName];

}

然后,模板将渲染 translate() 方法的输出,而不是实际的翻译字符串:

<h1><?php echo translate("page.headline"); ?></h1>
格式化

必须在模板中指明要为哪些键渲染翻译。

使用此格式来显示键名称而不是翻译:

{{__phrase_NameOfYourKey__}}

示例:

如果键 page.headline 位于模板中,则渲染字符串 {{__phrase_page.headline__}}

修改 translate() 辅助方法,以便以所需格式显示键名称:

function translate($keyName) {

  if ($phraseModeEnabled) {

    return "";

  } else {

    return $translations[$keyName];

  }

}

根据框架的不同,代码中的翻译辅助程序可以被覆盖,或者可以创建一个包装版本以在模板中使用。

示例:

const t = (key: string) => '{{__phrase_' + key + '__}}'

转义键名称和特殊字符

确保键名称已转换为可识别的格式。

当暴露给 In-context Editor 时,需要转义以下列表中的字符:

字符

转义序列

示例

<

[[[[[[html_open]]]]]]

{{__phrase__<key__}} 变为 {{__phrase__key[[[[[[html_open]]]]]]__}}

>

[[[[[[html_close]]]]]]

{{__phrase__key>__}} 变为 {{__phrase__[[[[[[html_close]]]]]]key__}}

自动大小写转换

默认情况下,In-context Editor 的文档解析器会将所有键转换为小写。如果遇到此行为相关的问题,并希望在 In-context Editor 中使用区分大小写的键,请禁用自动小写功能:

window.PHRASEAPP_CONFIG = {

  autoLowercase: false

}

自定义键装饰器

使用 In-context Editor 时,键名通常会用装饰器(默认情况下为花括号)包裹,以在文档上下文中生成唯一标识键:

{{__phrase_YOUR.KEY__}}

如果这导致与其他 libraries(例如,包括 AngularJS 和 Ember.js 在内的客户模板引擎)产生冲突,且它们使用了类似的语法,请在设置中更改 In-context Editor 的装饰器前缀和后缀。要告知 In-context Editor 解析器应查找哪些装饰器,请在 JavaScript 代码片段之前添加以下配置值:

window.PHRASEAPP_CONFIG = {

  prefix: '[[__',

  suffix: "__]]"

}

这会告知编辑器查找以 [[__ 开头并以 __]] 结尾的标记:

[[__phrase_YOUR.KEY__]]

如果使用 phraseapp-in-context-editor-ruby gem 来提供 In-context Editor 功能,请确保已配置装饰器:

PhraseApp::InContextEditor.configure do |config|

  config.prefix = "[[__"

  config.suffix = "__]]"

end

如果不使用该 gem,请确保在自定义代码中调整键名显示模式。

启用和禁用 In-context Editor

此设置仅在使用 phraseapp-in-context-editor-ruby gem 时可用。

In-context Editor 默认处于禁用状态。

可以显式启用或禁用 In-context Editor。这会影响 JavaScript 代码片段的包含(使用视图助手时)以及视图中装饰键名的渲染:

PhraseApp::InContextEditor.enabled = true|false

将标记绑定到环境变量的示例:

PhraseApp::InContextEditor.enabled = (ENV["IN_CONTEXT_EDITING"] == "1")

完全重新解析

如果将 In-context Editor 与使用虚拟 DOM(如 React)的 JavaScript 框架一起使用,请启用 fullReparse。这允许在检测到 DOM 更改时进行正确的重新解析:

window.PHRASEAPP_CONFIG = {

  fullReparse: true

}

将输出清理到网页

可以通过向 sanitize 属性提供一个函数,将 In-context Editor 配置为在将翻译插入网页之前对其进行转义或更改。

该函数接受翻译字符串作为第一个参数,并应返回一个字符串:

import escape from “lodash/escape”;

window.PHRASEAPP_CONFIG = {  

    sanitize: escape

}

单点登录

如果使用单点登录并希望在启用 SSO 的情况下初始化 In-context Editor,请在 JavaScript 代码片段之前添加以下配置值:

window.PHRASEAPP_CONFIG = {

  sso: {

    enabled: true,
    
    provider: 'saml',

    identifier: [insert_company_identifier]

  }

}

要要求用户使用 SSO 登录,请设置 enforced 参数:

window.PHRASEAPP_CONFIG = {

  sso: {

    enforced: true

  }

}

旧版 In-context Editor:设置

Web 框架安装

Angular 2 (ngx-translate)

要在该环境中安装 In-context Editor,请按照以下步骤操作:

  1. 使用 NPM 安装:

    npm install ngx-translate-phraseapp
  2. 配置:

    let config = {
      projectId: '<YOUR_PROJECT_ID>',
      phraseEnabled: true,
      prefix: "{{__",
      suffix: "__}}",
      fullReparse: true
    };

    项目的项目 ID 可以在项目设置中找到。

  3. 默认情况下,编辑器文档解析器会将所有键转换为小写。如果遇到此行为导致的问题,并且希望在编辑器中使用区分大小写的键,请禁用自动小写功能:

    let config = {
      // ...
      autoLowercase: false
    }
  4. 将这些代码片段添加到 Angular 应用中:

    app.component.ts

    import { initializePhraseAppEditor, PhraseAppCompiler} from 'ngx-translate-phraseapp'
    
    let config = {
      projectId: '<YOUR_PROJECT_ID>',
      phraseEnabled: true,
      prefix: "{{__",
      suffix: "__}}",
      fullReparse: true
    };
    
    initializePhraseAppEditor(config);

    app.module.ts

    import { TranslateModule, TranslateLoader, TranslateCompiler } from '@ngx-translate/core';
    import { HttpClientModule, HttpClient } from '@angular/common/http';
    import { PhraseAppCompiler } from 'ngx-translate-phraseapp'
    
    export function HttpLoaderFactory(http: HttpClient) {
      return new TranslateHttpLoader(http);
    }
    
    @NgModule({
      declarations: [
        AppComponent
      ],
      imports: [
        BrowserModule,
        HttpClientModule,
        TranslateModule.forRoot({
          loader: {
            provide: TranslateLoader,
            useFactory: HttpLoaderFactory,
            deps: [HttpClient]
          },
          compiler: {
            provide: TranslateCompiler,
            useClass: PhraseAppCompiler
          }
        }),
      ],
      providers: [],
      bootstrap: [AppComponent]
    })
代码示例

demo app 展示了 In-context Editor 与 Angular 和 ngx-translate 的集成。

AngularJS (angular-translate)

要在该环境中安装 In-context Editor,请按照以下步骤操作:

  1. 通过 Bower 安装 angular-phrase(或 手动下载):

    $ bower install angular-phrase
  2. 在加载 angular-translate 模块后,将 angular-phrase 模块添加到现有的 AngularJS 应用程序中:

    var myApp = angular.module("myApp", ['pascalprecht.translate', 'phrase']);
    
  3. 配置该模块:

    myApp.value("phraseProjectId", "YOUR-PROJECT-ID");
    
    myApp.value("phraseEnabled", true);
    
    myApp.value("phraseDecoratorPrefix", "");

    项目的项目 ID 可以在项目设置中找到。这将创建一个包含一些配置选项的初始化文件。

  4. 添加 phrase-javascript 标签到应用程序的 <head> 标签内:

    <phrase-javascript></phrase-javascript>
  5. 在任何网络浏览器中打开应用程序,即可看到应用到该应用程序的 In-context Editor。使用任何 Phrase 公司用户登录。

GitHub 上的 angular-phrase

代码示例

这个 demo 应用程序用于 angular-phrase,展示了如何使用 angular-translate 对 AngularJS 进行本地化。

Django

要在该环境中安装 In-context Editor,请按照以下步骤操作:

  1. 使用 pip 安装 django-phrase 包:

    $ pip install django-phrase
  2. 将 Phrase 添加到已安装应用的列表:

    INSTALLED_APPS = (
    
        'phrase',
    
    )
  3. 在模板中使用 phrase_i18n 模板标签:

    {% load phrase_i18n %}

    要允许 django-phrase 覆盖翻译方法,请在 i18n 之后加载 phrase_i18n

  4. 将 JavaScript 代码片段添加到布局中:

    {% phrase_javascript %}
  5. 使用这些选项为项目配置 In-context Editor:

    PHRASE_ENABLED = TruePHRASE_PROJECT_ID = 'YOUR_PROJECT_ID'PHRASE_PREFIX = '{{__'PHRASE_SUFFIX = '__}}'
  6. 在任何网络浏览器中打开应用程序,即可看到应用到该应用程序的 In-context Editor。使用任何 Phrase 公司用户登录。

Django adapter code on GitHub

代码示例

demo 应用程序演示了如何将 In-context Editor 与 Django 应用程序集成。

React (intl)

注释

此库可能无法在 IE11 或更旧的浏览器中工作。如果需要支持更旧的浏览器,请将 Babel 添加到构建管道中。

此库继承了 react-intl 包的通用组件。如果通过调用 initializePhraseAppEditor 启用了 Phrase,组件的行为将会更改。

要在该环境中安装 In-context Editor,请按照以下步骤操作:

  1. 通过 NPM 安装该包:

    npm install react-intl-phraseapp

    或从原文/源语构建:

    npm run dist
    npm install
  2. 配置:

    let config = {
      projectId: '<YOUR_PROJECT_ID>',
      phraseEnabled: true,
      prefix: "[[__",
      suffix: "__]]",
      fullReparse: true
    };

    项目的项目 ID 可以在项目设置中找到。

  3. 将代码片段添加到 react 应用:

    import {initializePhraseAppEditor} from 'react-intl-phraseapp'
    
    let config = {
      projectId: '<YOUR_PROJECT_ID>',
      phraseEnabled: true,
      prefix: "[[__",
      suffix: "__]]",
      fullReparse: true
    };
    
    initializePhraseAppEditor(config);
  4. 找到所有 FormattedMessage 的导入,并将原文/源语从 react-intl 更改为 react-intl-phraseapp

    import {FormattedMessage} from 'react-intl-phraseapp'
  5. 使用 jest 运行单元测试:

    npm test
代码示例

demo 展示了 Phrase In-context Editor 与 react-intl 的集成。

Ruby on Rails (i18n)

要在该环境中安装 In-context Editor,请按照以下步骤操作:

  1. phraseapp-in-context-editor-ruby gem 添加到您想要使用 In-context Editor 的环境:

    group :development do
      gem 'phraseapp-in-context-editor-ruby'
     end

    并通过执行 bundle 命令进行安装:

    $ bundle install
  2. 通过执行 Rails 生成器安装 phraseapp-in-context-editor-ruby gem:

    $ bundle exec rails generate phraseapp_in_context_editor:install --access-token=YOUR_ACCESS_TOKEN --project-id=YOUR_PROJECT_ID
    

    --access-token

    在个人资料设置中或通过 Authorizations API 创建和管理访问令牌。

    --project-id

    项目的项目 ID 可以在项目设置中找到。这将创建一个包含一些配置选项的初始化文件。

  3. 使用 phraseapp_in_context_editor_js 辅助程序将 JavaScript 代码片段添加到应用程序布局的 <head> 标签内:

    <head>
      ...
      <%= phraseapp_in_context_editor_js %>
      ...
    </head>
  4. 在任何网络浏览器中打开应用程序,即可看到应用到该应用程序的 In-context Editor。使用任何 Phrase 公司用户登录。

  5. 禁用 Turbolinks(如果已使用)

    Turbolinks 会在每次页面获取时从页面中移除所有 In-context Editor UI 元素。

    data-no-turbolink 属性添加到 <body> 标签:

    <body <%= PhraseApp::InContextEditor.enabled? ? "data-no-turbolink" : "" %>>
代码示例

demo 展示了 Phrase In-context Editor 与 react-i18next 的集成。

Spring

要在该环境中安装 In-context Editor,请按照以下步骤操作:

  1. 确保 package com.phraseapp.incontexteditor 在应用程序中可用。

  2. 设置正确的项目 ID 并在 PhraseAppConfiguration.class 中调整其他参数。

  3. 要通过 Phrase 渲染所有翻译,请将 bean 添加到应用程序中:

    @Bean
    
    @Conditional(PhraseAppEnabledCondition.class)
    
    public MessageSource messageSource() {
    
        return new PhraseAppMessageSource();
    
    }
  4. 通过将辅助工具公开为 bean,在模板中提供所需的 JavaScript 辅助工具:

    @Bean
    
    public PhraseAppJavascriptHeader phraseAppJavascriptHeader() {
    
        return new PhraseAppJavascriptHeader();
    
    }
  5. <script> 标签添加到每个页面 <head> 标签内的模板中:

    <head>
    
        <script th:utext="${@phraseAppJavascriptHeader.getHeader()}"></script>
    
    </head>
  6. 重启应用程序并使用 Phrase 用户凭据登录。

GitHub 上的示例应用程序源代码

如何像专业人士一样本地化 Spring 应用程序

Spring Boot Starter 包(由 ePages 提供)

Symfony 2.x

要在该环境中安装 In-context Editor,请按照以下步骤操作:

  1. 创建一个新的环境,In-context Editor 将在该环境中运行。在示例中,新环境命名为 translation

    创建一个新的配置文件:

    # app/config/config_translation.yml
    
    imports:
    
        - { resource: config.yml }
    
    parameters:
    
        translator.class: Acme\YourBundle\Translation\PhraseTranslator
  2. 创建一个控制器以使环境可通过浏览器访问:

    # web/app_translation.php
    
    <?php
    
    require_once __DIR__.'/../app/bootstrap.php.cache';
    
    require_once __DIR__.'/../app/AppKernel.php';
    
    use Symfony\Component\HttpFoundation\Request;
    
    $kernel = new AppKernel('translation', false);
    
    $kernel->handle(Request::createFromGlobals())->send();
  3. 覆盖标准翻译方法,以便向 In-context Editor 公开键名称:

    # Acme/YourBundle/Translation/PhraseTranslator.php
    
    <?php
    
    namespace Acme\YourBundle\Translation;
    
    use Symfony\Bundle\FrameworkBundle\Translation\Translator as BaseTranslator;
    
    class PhraseTranslator extends BaseTranslator
    
    {
    
        public function trans($id, array $parameters = array(), $domain = 'messages', $locale = null)
    
        {
    
            $prefix = "";
    
            if (!isset($locale)) {
    
                $locale = $this->getLocale();
    
            }
    
            if (!isset($this->catalogues[$locale])) {
    
                $this->loadCatalogue($locale);
    
            }
    
            if ($domain == 'routes') {
    
                // Return translated values for 'routes' domain
    
                return strtr($this->catalogues[$locale]->get((string) $id, $domain), $parameters);
    
            } else {
    
                // Return PhraseApp translation keys for all other domains
    
                return $prefix.$id.$suffix;
    
            }
    
        }
    
    }
  4. 将 JavaScript 代码片段添加到布局中:

    # Acme/YourBundle/Resources/views/layout.html.twig
  5. 在任何网络浏览器中打开应用程序,即可看到应用到该应用程序的 In-context Editor。使用任何 Phrase 公司用户登录。

Symfony 翻译文档

GitHub 上的 Symfony 2.x 适配器代码

Symfony 3.x

要在该环境中安装 In-context Editor,请按照以下步骤操作:

  1. 创建一个新的环境,In-context Editor 将在该环境中运行。在示例中,新环境命名为 translation

    创建一个新的配置文件:

    # app/config/config_translation.yml
    
    imports:
    
       - { resource: config.yml }
  2. 创建一个控制器以使环境可通过浏览器访问:

    # web/app_translation.php
    
    <?php
    
    use Symfony\Component\HttpFoundation\Request;
    
    $loader = require __DIR__.'/../app/autoload.php';
    
    $kernel = new AppKernel('translation', true);
    
    $kernel->loadClassCache();
    
    $request = Request::createFromGlobals();
    
    $response = $kernel->handle($request);
    
    $response->send();
    
    $kernel->terminate($request, $response);
  3. 覆盖标准翻译方法,以便向 In-context Editor 公开键名称:

    # src/AppBundle/Translation/PhraseTranslator.php
    
    <?php
    
    namespace AppBundle\Translation;
    
    use Symfony\Bundle\FrameworkBundle\Translation\Translator as BaseTranslator;
    
    class PhraseTranslator extends BaseTranslator
    
    {
    
       public function trans($id, array $parameters = array(), $domain = 'messages', $locale = null)
    
       {
    
           $prefix = "";
    
           if (null === $domain) {
    
               $domain = 'messages';
    
           }
    
           // Return ID of translation key with pre- and suffix for PhraseApp
    
           return $prefix.$id.$suffix;
    
       }
    
    }
  4. 确保在将 bundle 与编译器传递一起使用时,该类始终被覆盖:

    # src/AppBundle/DependencyInjection/Compiler/OverrideServiceCompilerPass.php
    
    <?php
    
    namespace AppBundle\DependencyInjection\Compiler;
    
    use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
    
    use Symfony\Component\DependencyInjection\ContainerBuilder;
    
    class OverrideServiceCompilerPass implements CompilerPassInterface
    
    {
    
       public function process(ContainerBuilder $container)
    
       {
    
           $definition = $container->getDefinition('translator.default');
    
           $definition->setClass('AppBundle\Translation\PhraseTranslator');
    
       }
    
    }
  5. 如果使用单独的编译器传递,请在 bundle 类的 build() 方法中注册它们:

    # src/AppBundle/AppBundle.php
    
    <?php
    
    namespace AppBundle;
    
    use Symfony\Component\HttpKernel\Bundle\Bundle;
    
    use Symfony\Component\DependencyInjection\ContainerBuilder;
    
    use AppBundle\DependencyInjection\Compiler\OverrideServiceCompilerPass;
    
    class AppBundle extends Bundle
    
    {
    
       public function build(ContainerBuilder $container)
    
       {
    
           parent::build($container);
    
           if($container->getParameter("kernel.environment") == 'translation') {
    
               $container->addCompilerPass(new OverrideServiceCompilerPass());
    
           };
    
       }
    
    }
  6. 将 JavaScript 代码片段添加到布局中:

    # src/YourBundle/Resources/views/layout.html.twig
  7. 在任何网络浏览器中打开应用程序,即可看到应用到该应用程序的 In-context Editor。使用任何 Phrase 公司用户登录。

Symfony 翻译文档

Vue I18n

注释

Vue I18n Phrase In-context Editor 支持所有 8.17.5 及更高版本的 Vue I18n。此库可能适用于以前的版本,但它们不受官方支持,也不会获得任何特定的更新或错误修复。

要在该环境中安装 In-context Editor,请按照以下步骤操作:

  1. 使用首选的包管理器安装该包:

    # yarn
    yarn add vue-i18n-phrase-in-context-editor
    
    # npm
    npm install vue-i18n-phrase-in-context-editor

    或通过 CDN 加载(手动注册 window['vue-i18n-phrase-in-context-editor'] ):

    <script src="https://unpkg.com/vue-i18n-phrase-in-context-editor/dist/vue-i18n-phrase-in-context-editor.umd.min.js"></script>
    
  2. 引导(示例):

    import Vue from 'vue';
    import VueI18n from 'vue-i18n';
    
    Vue.use(VueI18n);
    
    const i18n = new VueI18n({
      locale: process.env.VUE_APP_I18N_LOCALE || 'en',
      fallbackLocale: process.env.VUE_APP_I18N_FALLBACK_LOCALE || 'en',
      messages: {
          hello: 'Hello world!'
      }
    });
    
    new Vue({
      i18n,
      render: h => h(App)
    }).$mount('#app');

    要集成该库:

    1. 导入 Vue I18n Phrase In-context Editor 库。

    2. 创建新的 Vue I18n Phrase In-context Editor 实例,将 Vue I18n 实例作为第一个参数传递,并将 Phrase Config 作为第二个参数。

配置选项和示例方法

使用旧版 In-context Editor

Ajax 模式

In-context Editor 使用突变观察者支持 Ajax 和 DOM 操作(即通过 JavaScript)。

Ajax 模式在某些情况下可能会导致问题,并且在使用 In-context Editor 时可能会导致严重的性能问题。要禁用 Ajax 模式,请在 JavaScript 代码片段之前添加以下配置值:

window.PHRASEAPP_CONFIG = {

  ajaxObserver: false

}

调试模式

要启用调试模式,请在 JavaScript 代码片段之前添加以下配置值:

window.PHRASEAPP_CONFIG = {

  debugMode: true

}

强制区域

要在启动 In-context Editor 时显式设置特定的区域,请使用 forceLocale 设置。这对于在 In-context Editor 中预选当前在您的 Web 应用程序中显示的区域也很有用:

window.PHRASEAPP_CONFIG = {

  forceLocale: "pt-BR"

}

忽略的键

此设置仅在使用 phraseapp-in-context-editor-ruby gem 时可用。

可以排除某些键,使其不使用 In-context Editor 进行渲染。在使用 Rails 时,可以忽略诸如错误消息或日期和时间格式键之类的数据键。要将键排除在 phraseapp-in-context-editor-ruby gem 的自动处理之外,请将这些键的数组添加到 phraseapp_in_context_editor.rb 初始化文件中。也可以使用通配符:

PhraseApp::InContextEditor.configure do |config|

  config.ignored_keys = ["date.*", "forbidden.key",   "errors.messages*"]

end

与这些模式中任何一个匹配的键将不会被 In-context Editor 访问,并会正常渲染。

这篇文章有帮助吗?

Sorry about that! In what way was it not helpful?

The article didn’t address my problem.
I couldn’t understand the article.
The feature doesn’t do what I need.
Other reason.

Note that feedback is provided anonymously so we aren't able to reply to questions.
If you'd like to ask a question, submit a request to our Support team.
Thank you for your feedback.