-
Team, Professional, Business and Enterprise plans
Get in touch with Sales for licensing questions.
-
Advanced and Enterprise plan (Legacy)
Get in touch with Sales for licensing questions.
The In-Context editor is designed to help translators get things done more efficiently and translate a website page through direct integration with the Strings translation editor.
Currently, two versions are available:
-
The In-Context editor:
Includes new functionalities (multilingual view, layout options, batch actions, collaboration features, etc.) and UI from the translation editor.
After installing the In-Context editor, it can be customized to work with many technologies.
To use the In-Context editor, the application requires:
-
Web-based websites, web applications, mobile sites, etc.
-
Translators have access to the the web server running the editor. This could be a local environment if required.
-
A key-value localization file structure.
Web sites with translatable strings extracted and a view layer that uses a key-value structure to render translations.
-
Key names exposed to the view or template layer.
-
JavaScript snippet that renders the editor.
-
Ideally, a dedicated environment for translations. This can be a clone of a staging environment and although more work to initially set up, provides a better workflow and more stability.
If a dedicated environment is not possible, an existing staging environment can be used with the option of enabling the In-Context Editor as needed.
Include the JavaScript snippet in the application layout.
The snippet includes the code required to:
-
Communicate with the Phrase Strings API.
-
Render the user interface.
-
Provide login.
Project ID
is found in project settings.
Account ID
is found in Strings organization settings.
Sample:
<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://d2bgdldl6xit7z.cloudfront.net/latest/ice/index.js"></script>
Note
i18next Phrase In-Context Editor Post Processor supports all i18next versions newer than 19.5.1. Although this library might work with previous versions as well, they are not officially supported and might not get any specific updates or bug fixes.
To install the In-Context editor in this environment, follow these steps:
-
Install the i18next-phrase-in-context-editor-post-processor library with preferred package manager:
# yarn yarn add i18next-phrase-in-context-editor-post-processor # npm npm install i18next-phrase-in-context-editor-post-processor
Note
Recommended library versions are 1.4.0 or newer.
or load it via CDN:
<script src="https://unpkg.com/i18next-phrase-in-context-editor-post-processor"></script>
-
Bootstrap (sample):
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 });
To integrate the library:
-
Import
PhraseInContextEditorPostProcessor
from i18next-phrase-in-context-editor-post-processor library. -
Create new i18next Phrase In-Context Editor Post Processor instance, passing PhraseConfig as the argument.
-
Pass newly created i18next Phrase In-Context Editor Post Processor instance to i18next use method.
-
Add
phraseInContextEditor
string to postProcess array property (passed within the configuration object of i18next init method).
-
-
Add the ICE JavaScript snippet to the i18next instance in the setup.
Sample snippet:
i18nextInstance.use(new PhraseInContextEditorPostProcessor({ phraseEnabled: true, projectId: '00000000000000004158e0858d2fa45c', accountId: '0bed59e5', }))
Note
accountId
must be provided to setup ICE successfully. The account ID is found in Strings organization settings.If required, configure
useOldICE
attribute to switch to the old ICE:i18nextInstance.use(new PhraseInContextEditorPostProcessor({ phraseEnabled: true, projectId: '00000000000000004158e0858d2fa45c', accountId: '0bed59e5', useOldICE: true, }))
-
Start the In-Context editor.
-
Open the application in a web browser to display the In-Context editor. Sign in with any Phrase organization user.
Note
Vue I18n Phrase In-Context Editor supports all Vue I18n versions 8.17.5 and newer. This library may work with previous versions but they are not officialy supported and will not get any specific updates or bug fixes.
To install the In-Context editor in this environment, follow these steps:
-
Install the newest package with preferred package manager:
# yarn yarn add vue-i18n-phrase-in-context-editor # npm npm install vue-i18n-phrase-in-context-editor
or load with CDN (register manually
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>
-
Bootstrap (sample):
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');
To integrate the library:
Note
This library may not work with IE11 or older browsers. Add Babel to the build pipeline if older browser support is required.
This library inherits common components of the react-intl packages. If Phrase is enabled by calling initializePhraseAppEditor
, the behavior of the components will change.
To install the In-Context editor in this environment, follow these steps:
-
Install the newest package via NPM:
npm install react-intl-phraseapp
or build from source:
npm run dist
npm install
-
Configure:
let config = { projectId: '<YOUR_PROJECT_ID>', accountId: '<YOUR_ACCOUNT_ID>', phraseEnabled: true, prefix: "[[__", suffix: "__]]", fullReparse: true };
Project ID of a project is found in project settings.
Account ID is found in Strings organization settings.
-
Add the snippet to the react app:
import {initializePhraseAppEditor} from 'react-intl-phraseapp' let config = { projectId: '<YOUR_PROJECT_ID>', accountId: '<YOUR_ACCOUNT_ID>', phraseEnabled: true, prefix: "[[__", suffix: "__]]", fullReparse: true }; initializePhraseAppEditor(config);
-
Find all imports of
FormattedMessage
, and change the source fromreact-intl
toreact-intl-phraseapp
.import {FormattedMessage} from 'react-intl-phraseapp'
-
Run unit tests using jest:
npm test
Code sample
This demo shows an integration of the Phrase In-Context editor with react-intl.
Prerequisites
-
Sign up for a Phrase Strings account.
-
Use ngx-translate module for localization in Angular 2 applications.
To install the In-Context editor in this environment, follow these steps:
-
Install with NPM:
npm install ngx-translate-phraseapp
-
Configure:
import { initializePhraseAppEditor, PhraseConfig } from 'ngx-translate-phraseapp'; let config: PhraseConfig = { projectId: '<YOUR_PROJECT_ID>', accountID: '<YOUR_ACCOUNT_ID>' phraseEnabled: true, };
Project ID of a project is found in project settings.
Account ID is found in Strings organization settings.
If required, configure
useOldICE
attribute to switch to the old ICE:let config = { projectId: '<YOUR_PROJECT_ID>', accountID: '<YOUR_ACCOUNT_ID>', phraseEnabled: true, useOldICE: true, }; initializePhraseAppEditor(config);
If required, add the US specific URLs to enable working through the US data center:
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",
-
By default, the editor’s document parser converts all keys to lowercase. If experiencing issues with this behavior and want to use case-sensitive keys within the editor, disable the automatic lowercase feature:
let config = { // ... autoLowercase: false }
-
Add these snippets to the Angular app:
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] })
Code sample
This demo app showcases an integration of the In-Context editor with Angular and ngx-translate.
Note
This library might not work out-of-the-box for older browsers or Microsoft IE11. Add Babel to the build pipeline if those browsers need to be supported.
Prerequisites
To install the In-Context editor in this environment, follow these steps:
-
Add the
phraseapp-in-context-editor-ruby
library to the desired environment using one of the following methods:-
Via Gem
gem install phraseapp-in-context-editor-ruby
-
Via Bundler
Add it to the
Gemfile
:gem 'phraseapp-in-context-editor-ruby
-
Build directly from source to get the latest and greatest:
bundle && gem build
-
-
Create the initializer file by executing the Rails generator:
rails generate phraseapp_in_context_editor:install --account_id=<YOUR_ACCOUNT_ID> --project-id=<YOUR_PROJECT_ID>
Project ID of a project is found in project settings.
Account ID is found in Strings organization settings.
-
Add the Ruby snippet to the application layout
app/views//layouts/application.html.erb
:<%= load_in_context_editor %>
-
Add the following configuration to the initializer
/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"
If required, set the US data center to enable working with US endpoints:
config.enabled = true config.project_id = "YOUR_PROJECT_ID" config.account_id = "YOUR_ACCOUNT_ID" config.datacenter = "us"
-
Open the application in any web browser to see the In-Context editor applied to the app. Sign in with any Phrase organization user.
Code sample
This demo shows an integration of the Phrase In-Context editor with react-i18next.
Prerequisites
Note
Old version of the ICE is not available since version 2.0.0.
To install the In-Context editor in this environment, follow these steps:
-
Install the
django-phrase
package with pip:$ pip install django-phrase
-
Add Phrase to the list of installed apps:
INSTALLED_APPS = ( 'phrase', )
-
Add the following template snippets to the layout file
templates/base_generic.html
or equivalent:{% load phrase_i18n %} {% phrase_javascript %}
-
Use the phrase_i18n template tag in templates (for example,
demo/ice_demo/templates/index.html
):{% load phrase_i18n %}
-
Add the following configuration to
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 = "__}}"
Project ID of a project is found in project settings.
Account ID is found in Strings organization settings.
In case of issues, it is possible to integrate the JavaScript snippet manually.
-
Open the application in any web browser to see the In-Context editor applied to the app. Sign in with any Phrase organization user.
Code sample
This demo application demonstrates how to integrate the In-Context editor with a Django application.
Prerequisites
Note
Old version of the ICE is not available since version 2.0.0.
To install the In-Context editor in this environment, follow these steps:
-
Install the
Flask-Phrase
package with pip:pip install Flask-Phrase
-
Add the following configuration to the Flask app (
app.config
orconfig.py
):PHRASEAPP_ENABLED = True PHRASEAPP_PREFIX = '{{__' PHRASEAPP_SUFFIX = '__}}'
The app code should look similar to this:
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)
-
Add the Phrase JavaScript snippet to the base layout file with the following tag (it should go inside the template file's section):
<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://d2bgdldl6xit7z.cloudfront.net/latest/ice/index.js' var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(phrasejs, s); })(); </script>
Project ID of a project is found in project settings.
Account ID is found in Strings organization settings.
If required, set the US data center to enable working with US endpoints:
window.PHRASEAPP_CONFIG = { projectId: "YOUR-PROJECT-ID", accountId: "YOUR-ACCOUNT-ID", datacenter: "us", };
When PHRASEAPP_ENABLED = True
, the package modifies the returning values from translation functions to present a format which the ICE can read. When set to False
, it will fall back to standard Flask-Babel's gettext functions.
Code sample
This demo application demonstrates how to integrate the In-Context editor with a Flask application.
Prerequisites
Note
Version 2.0.0 supports Symfony 5 and higher. If using Symfony 2, 3, or 4, check out the old version of the ICE.
To integrate the In-Context editor with the Symfony application, follow these steps:
-
Copy
PhraseStringsInContextEditor
and its contents into the/src/Service
folder of the repository or the desired location. If placed elsewhere, adjust the namespace accordingly. -
Adjust
config/services.yaml
to decorate thetranslator
service with Phrase's adapter:services: ... App\Service\PhraseStringsInContextEditor\Translator: decorates: translator
-
Add the following JavaScript snippet to the base or Twig layout template between the
{% block javascripts %}
so that the In-Context Editor can read the web page:<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://d2bgdldl6xit7z.cloudfront.net/latest/ice/index.js' var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(phrasejs, s); })(); </script>
The Symfony application is now connected to the In-Context Editor.
Project ID of a project is found in project settings.
Account ID is found in Strings organization settings.
If required, set the US data center to enable working with US endpoints:
window.PHRASEAPP_CONFIG = { projectId: "YOUR-PROJECT-ID", accountId: "YOUR-ACCOUNT-ID", datacenter: "us", };
-
Reload the application and login with Phrase credentials to start the translation process directly on the web page.
Code sample
This demo application demonstrates how to integrate the In-Context editor with a Symfony application.
Typically, a view layer renders translations by passing the name of a translatable string (i.e., the key) to some sort of translation method or view helper.
Sample PHP code:
$translations = array( "page.headline" => "Some Headline", "page.link.label" => "I am a link", "page.link.hint" => "Click me" ) function translate($keyName) { return $translations[$keyName]; }
The template would then render the output of the translate()
method instead of the actual translated string:
<h1><?php echo translate("page.headline"); ?></h1>
Formatting
It must be indicated in the template which keys to render translations for.
Use this formatting to expose key names instead of translations:
{{__phrase_NameOfYourKey__}}
Example:
If the key page.headline
is in the template, render the string {{__phrase_page.headline__}}
.
Modify the translate()
helper method so as to expose key names in the required format:
function translate($keyName) { if ($phraseModeEnabled) { return ""; } else { return $translations[$keyName]; } }
Depending on framework, translation helpers in the code can be overridden or a wrapped version can be created to use in templates.
Example:
const t = (key: string) => '{{__phrase_' + key + '__}}'
Ensure key names are converted to a recognizable format.
Characters in the following list need to be escaped when exposed to the In-Context Editor:
Character |
Escape sequence |
Example |
---|---|---|
< |
|
{{__phrase__<key__}} becomes {{__phrase__key[[[[[[html_open]]]]]]__}} |
> |
|
{{__phrase__key>__}} becomes {{__phrase__[[[[[[html_close]]]]]]key__}} |
By default, the In-Context editor’s document parser converts all keys to lowercase. If experiencing issues with this behavior and want to use case-sensitive keys within the In-Context Editor, disable the automatic lowercase feature:
window.PHRASEAPP_CONFIG = { autoLowercase: false }
When using the In-Context editor, key names are typically wrapped with decorators (curly braces, by default) to generate unique identification keys within the context of a document:
{{__phrase_YOUR.KEY__}}
If this causes conflicts with other libraries (e.g., client-side template engines, including AngularJS and Ember.js) that use a similar syntax, change the In-Context editor’s decorator prefix and suffix in the setup. To tell the In-Context editor which decorators the parser should look for, add the following configuration values before the JavaScript snippet:
window.PHRASEAPP_CONFIG = { prefix: '[[__', suffix: "__]]" }
This tells the editor to look for tags beginning with [[__ and ending with __]]:
[[__phrase_YOUR.KEY__]]
If using the phraseapp-in-context-editor-ruby gem to provide In-Context editor functionality, ensure decorators are configured:
PhraseApp::InContextEditor.configure do |config| config.prefix = "[[__" config.suffix = "__]]" end
If not using the gem, ensure the key name exposure pattern is adjusted in the custom code.
This setting is only available when using the phraseapp-in-context-editor-ruby gem.
The In-Context editor is disabled by default.
The In-Context editor can be explicitly enabled or disabled. This affects the inclusion of the JavaScript snippet (when using the view helper) and the rendering of the decorated key names in views:
PhraseApp::InContextEditor.enabled = true|false
Example of binding the flag to an environment variable:
PhraseApp::InContextEditor.enabled = (ENV["IN_CONTEXT_EDITING"] == "1")
Enable fullReparse
ifusing the In-Context editor with a JavaScript framework that uses Virtual DOM such as React. This allows proper reparsing when DOM changes are detected:
window.PHRASEAPP_CONFIG = { fullReparse: true }
The In-Context editor can be configured to escape or alter translations before they are inserted into the webpage by providing a function to the sanitize property.
The function accepts the translation string as the first argument and should return a string:
import escape from “lodash/escape”; window.PHRASEAPP_CONFIG = { sanitize: escape }
If using single sign-on and want to initialize the In-Context editor with SSO enabled, add the following configuration value before the JavaScript snippet:
window.PHRASEAPP_CONFIG = { sso: { enabled: true, provider: 'saml', identifier: [insert_company_identifier] } }
To require users to sign on using SSO, set the enforced parameter:
window.PHRASEAPP_CONFIG = { sso: { enforced: true } }
To install the In-Context editor in this environment, follow these steps:
-
Install with NPM:
npm install ngx-translate-phraseapp
-
Configure:
let config = { projectId: '<YOUR_PROJECT_ID>', phraseEnabled: true, prefix: "{{__", suffix: "__}}", fullReparse: true };
Project ID of a project is found in project settings.
-
By default, the editor’s document parser converts all keys to lowercase. If experiencing issues with this behavior and want to use case-sensitive keys within the editor, disable the automatic lowercase feature:
let config = { // ... autoLowercase: false }
-
Add these snippets to the Angular app:
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] })
Code sample
This demo app showcases an integration of the In-Context editor with Angular and ngx-translate.
To install the In-Context editor in this environment, follow these steps:
-
Install angular-phrase via Bower (or download manually):
$ bower install angular-phrase
-
Add the angular-phrase module to existing AngularJS application after loading the angular-translate module:
var myApp = angular.module("myApp", ['pascalprecht.translate', 'phrase']);
-
Configure the module:
myApp.value("phraseProjectId", "YOUR-PROJECT-ID"); myApp.value("phraseEnabled", true); myApp.value("phraseDecoratorPrefix", "");
Project ID of a project is found in project settings. This creates an initialization file with some configuration options.
-
Add the
phrase-javascript
directive to the application inside the<head>
tag:<phrase-javascript></phrase-javascript>
-
Open the application in any web browser to see the In-Context editor applied to the app. Sign in with any Phrase organization user.
Code sample
This demo application for angular-phrase shows how to localize AngularJS with angular-translate.
To install the In-Context editor in this environment, follow these steps:
-
Install the
django-phrase
package with pip:$ pip install django-phrase
-
Add Phrase to the list of installed apps:
INSTALLED_APPS = ( 'phrase', )
-
Use the phrase_i18n template tag in templates:
{% load phrase_i18n %}
To allow
django-phrase
to override translation methods, load phrase_i18n after i18n. -
Add the JavaScript snippet to the layout:
{% phrase_javascript %}
-
Configure the In-Context Editor for the project with these options:
PHRASE_ENABLED = TruePHRASE_PROJECT_ID = 'YOUR_PROJECT_ID'PHRASE_PREFIX = '{{__'PHRASE_SUFFIX = '__}}'
-
Open the application in any web browser to see the In-Context editor applied to the app. Sign in with any Phrase organization user.
Code sample
This demo application demonstrates how to integrate the In-Context editor with a Django application.
Note
This library may not work with IE11 or older browsers. Add Babel to the build pipeline if older browser support is required.
This library inherits common components of the react-intl packages. If Phrase is enabled by calling initializePhraseAppEditor
, the behavior of the components will change.
To install the In-Context editor in this environment, follow these steps:
-
Install the package via NPM:
npm install react-intl-phraseapp
or build from source:
npm run dist
npm install
-
Configure:
let config = { projectId: '<YOUR_PROJECT_ID>', phraseEnabled: true, prefix: "[[__", suffix: "__]]", fullReparse: true };
Project ID of a project is found in project settings.
-
Add the snippet to the react app:
import {initializePhraseAppEditor} from 'react-intl-phraseapp' let config = { projectId: '<YOUR_PROJECT_ID>', phraseEnabled: true, prefix: "[[__", suffix: "__]]", fullReparse: true }; initializePhraseAppEditor(config);
-
Find all imports of
FormattedMessage
, and change the source fromreact-intl
toreact-intl-phraseapp
.import {FormattedMessage} from 'react-intl-phraseapp'
-
Run unit tests using jest:
npm test
Code sample
This demo shows an integration of the Phrase In-Context editor with react-intl.
To install the In-Context editor in this environment, follow these steps:
-
Add the
phraseapp-in-context-editor-ruby
gem to the environment you want to use the In-Context Editor with:group :development do gem 'phraseapp-in-context-editor-ruby' end
and install it by executing the bundle command:
$ bundle install
-
Install the
phraseapp-in-context-editor-ruby
gem by executing the Rails generator:$ bundle exec rails generate phraseapp_in_context_editor:install --access-token=YOUR_ACCESS_TOKEN --project-id=YOUR_PROJECT_ID
--access-token
Create and manage access tokens in profile settings or via the Authorizations API.
--project-id
Project ID of a project is found in project settings. This creates an initialization file with some configuration options.
-
Add the JavaScript snippet to your application layout within the
<head>
tag by using thephraseapp_in_context_editor_js
helper:<head> ... <%= phraseapp_in_context_editor_js %> ... </head>
-
Open the application in any web browser to see the In-Context editor applied to the app. Sign in with any Phrase organization user.
-
Disable Turbolinks (if used)
Turbolinks removes all In-Context Editor UI elements from the page on every page fetch.
Add the
data-no-turbolink
attribute to the<body>
tag:<body <%= PhraseApp::InContextEditor.enabled? ? "data-no-turbolink" : "" %>>
Code sample
This demo shows an integration of the Phrase In-Context editor with react-i18next.
To install the In-Context editor in this environment, follow these steps:
-
Ensure the package
com.phraseapp.incontexteditor
is available in the app. -
Set the correct project ID and adjust the other parameters in
PhraseAppConfiguration.class
. -
To render all translations through Phrase, add the bean to the application:
@Bean @Conditional(PhraseAppEnabledCondition.class) public MessageSource messageSource() { return new PhraseAppMessageSource(); }
-
Provide the required JavaScript helper in the templates by exposing the helper as a bean:
@Bean public PhraseAppJavascriptHeader phraseAppJavascriptHeader() { return new PhraseAppJavascriptHeader(); }
-
Add the
<script>
tag to your templates within each page’s<head>
tag:<head> <script th:utext="${@phraseAppJavascriptHeader.getHeader()}"></script> </head>
-
Restart the application and sign in with Phrase user credentials.
Example application source code on GitHub
To install the In-Context editor in this environment, follow these steps:
-
Create a new environment in which the In-Context editor will run. In the example, the new environment is named
translation
.Create a new configuration file:
# app/config/config_translation.yml imports: - { resource: config.yml } parameters: translator.class: Acme\YourBundle\Translation\PhraseTranslator
-
Create a controller to make the environment browser accessible:
# 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();
-
Override the standard translation method in order to expose the key names to the 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; } } }
-
Add the JavaScript snippet to the layout:
# Acme/YourBundle/Resources/views/layout.html.twig
-
Open the application in any web browser to see the In-Context editor applied to the app. Sign in with any Phrase organization user.
To install the In-Context editor in this environment, follow these steps:
-
Create a new environment in which the In-Context editor will run. In the example, the new environment is named
translation
.Create a new configuration file:
# app/config/config_translation.yml imports: - { resource: config.yml }
-
Create a controller to make the environment browser accessible:
# 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);
-
Override the standard translation method in order to expose the key names to the 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; } }
-
Ensure sure the class is always overridden when the bundle is used with a compiler pass:
# 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'); } }
-
If using separate compiler passes, register them in the build() method of the bundle class:
# 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()); }; } }
-
Add the JavaScript snippet to the layout:
# src/YourBundle/Resources/views/layout.html.twig
-
Open the application in any web browser to see the In-Context editor applied to the app. Sign in with any Phrase organization user.
Note
Vue I18n Phrase In-Context Editor supports all Vue I18n versions 8.17.5 and newer. This library may work with previous versions but they are not officially supported and will not get any specific updates or bug fixes.
To install the In-Context editor in this environment, follow these steps:
-
Install the package with preferred package manager:
# yarn yarn add vue-i18n-phrase-in-context-editor # npm npm install vue-i18n-phrase-in-context-editor
or load with CDN (register manually
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>
-
Bootstrap (sample):
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');
To integrate the library:
The In-Context Editor supports Ajax and DOM manipulation (i.e., via JavaScript) using mutation observers.
Ajax mode can cause problems in some cases, and may result in severe performance issues when using the In-Context editor. To disable Ajax mode, add the following configuration value before the JavaScript snippet:
window.PHRASEAPP_CONFIG = { ajaxObserver: false }
To enable debug mode, add the following configuration value before the JavaScript snippet:
window.PHRASEAPP_CONFIG = { debugMode: true }
To set a specific locale explicitly when starting the In-Context editor,use the forceLocale
setting. This is useful for preselecting the locale currently displayed in your web application in the In-Context editor as well:
window.PHRASEAPP_CONFIG = { forceLocale: "pt-BR" }
This setting is only available when using the phraseapp-in-context-editor-ruby gem.
Keys can be excluded from being rendered with the In-Context editor. When working with Rails, keys may be ignored for data such as error messages or date and time format keys. To exclude keys from being handled automatically by the phraseapp-in-context-editor-ruby gem, add an array of the keys to phraseapp_in_context_editor.rb
initialization file. Wildcards can also be used:
PhraseApp::InContextEditor.configure do |config| config.ignored_keys = ["date.*", "forbidden.key", "errors.messages*"] end
Keys matching any of these patterns will not be made accessible to the In-Context editor and are rendered normally.