2020-10-30 14:08:56 -04:00
---
2020-11-17 10:09:28 -05:00
stage: Manage
group: Import
2020-11-26 01:09:20 -05:00
info: To determine the technical writer assigned to the Stage/Group associated with this page, see https://about.gitlab.com/handbook/engineering/ux/technical-writing/#assignments
2020-10-30 14:08:56 -04:00
---
2017-05-16 14:26:12 -04:00
# Internationalization for GitLab
2020-02-06 10:09:11 -05:00
> [Introduced](https://gitlab.com/gitlab-org/gitlab-foss/-/merge_requests/10669) in GitLab 9.2.
2017-05-16 14:26:12 -04:00
2017-10-09 05:36:07 -04:00
For working with internationalization (i18n),
[GNU gettext ](https://www.gnu.org/software/gettext/ ) is used given it's the most
2021-06-08 17:10:05 -04:00
used tool for this task and there are many applications that help us work with it.
2017-05-16 14:26:12 -04:00
2020-12-07 22:09:37 -05:00
NOTE:
2021-06-08 17:10:05 -04:00
All `rake` commands described on this page must be run on a GitLab instance. This instance is
usually the GitLab Development Kit (GDK).
2020-09-15 20:09:37 -04:00
2021-06-08 17:10:05 -04:00
## Setting up the GitLab Development Kit (GDK)
2017-05-25 15:21:53 -04:00
2021-06-08 17:10:05 -04:00
To work on the [GitLab Community Edition ](https://gitlab.com/gitlab-org/gitlab-foss )
project, you must download and configure it through the [GDK ](https://gitlab.com/gitlab-org/gitlab-development-kit/blob/main/doc/set-up-gdk.md ).
2017-05-25 15:21:53 -04:00
2020-11-03 19:09:12 -05:00
After you have the GitLab project ready, you can start working on the translation.
2017-05-25 15:21:53 -04:00
2017-05-16 14:26:12 -04:00
## Tools
2017-10-09 05:36:07 -04:00
The following tools are used:
2017-05-16 14:26:12 -04:00
2021-06-08 17:10:05 -04:00
- [`gettext_i18n_rails` ](https://github.com/grosser/gettext_i18n_rails ):
this gem allows us to translate content from models, views, and controllers. It also gives us
access to the following Rake tasks:
- `rake gettext:find` : parses almost all the files from the Rails application looking for content
marked for translation. It then updates the PO files with this content.
- `rake gettext:pack` : processes the PO files and generates the binary MO files that the
application uses.
- [`gettext_i18n_rails_js` ](https://github.com/webhippie/gettext_i18n_rails_js ):
this gem makes the translations available in JavaScript. It provides the following Rake task:
- `rake gettext:po_to_json` : reads the contents of the PO files and generates JSON files that
contain all the available translations.
- PO editor: there are multiple applications that can help us work with PO files. A good option is
[Poedit ](https://poedit.net/download ),
which is available for macOS, GNU/Linux, and Windows.
2017-05-16 14:26:12 -04:00
## Preparing a page for translation
2021-06-08 17:10:05 -04:00
There are four file types:
2017-05-16 14:26:12 -04:00
2021-06-08 17:10:05 -04:00
- Ruby files: models and controllers.
- HAML files: view files.
- ERB files: used for email templates.
- JavaScript files: we mostly work with Vue templates.
2017-05-16 14:26:12 -04:00
### Ruby files
If there is a method or variable that works with a raw string, for instance:
```ruby
def hello
"Hello world!"
end
```
Or:
```ruby
hello = "Hello world!"
```
2021-06-08 17:10:05 -04:00
You can mark that content for translation with:
2017-05-16 14:26:12 -04:00
```ruby
def hello
_("Hello world!")
end
```
Or:
```ruby
hello = _("Hello world!")
```
2021-06-08 17:10:05 -04:00
Be careful when translating strings at the class or module level since these are only evaluated once
at class load time. For example:
2020-01-23 19:08:51 -05:00
```ruby
validates :group_id, uniqueness: { scope: [:project_id], message: _("already shared with this group") }
```
2021-06-08 17:10:05 -04:00
This is translated when the class loads and results in the error message always being in the default
locale. Active Record's `:message` option accepts a `Proc` , so do this instead:
2020-01-23 19:08:51 -05:00
```ruby
validates :group_id, uniqueness: { scope: [:project_id], message: -> (object, data) { _("already shared with this group") } }
```
2021-06-08 17:10:05 -04:00
Messages in the API (`lib/api/` or `app/graphql` ) do not need to be externalized.
2019-06-19 02:29:03 -04:00
2017-05-16 14:26:12 -04:00
### HAML files
Given the following content in HAML:
```haml
%h1 Hello world!
```
You can mark that content for translation with:
```haml
%h1= _("Hello world!")
```
### ERB files
Given the following content in ERB:
```erb
< h1 > Hello world!< / h1 >
```
You can mark that content for translation with:
```erb
< h1 > < %= _("Hello world!") %>< / h1 >
```
### JavaScript files
2018-02-15 12:17:13 -05:00
In JavaScript we added the `__()` (double underscore parenthesis) function that
you can import from the `~/locale` file. For instance:
2017-05-16 14:26:12 -04:00
2020-05-19 14:08:11 -04:00
```javascript
2018-02-15 12:17:13 -05:00
import { __ } from '~/locale';
const label = __ ('Subscribe');
2017-07-21 02:55:45 -04:00
```
2021-06-08 17:10:05 -04:00
To test JavaScript translations you must:
- Change the GitLab localization to a language other than English.
- Generate JSON files by using `bin/rake gettext:po_to_json` or `bin/rake gettext:compile` .
2020-09-04 11:08:46 -04:00
### Vue files
2021-06-08 17:10:05 -04:00
In Vue files, we make the following functions available:
- `__()` (double underscore parenthesis)
- `s__()` (namespaced double underscore parenthesis)
You can therefore import from the `~/locale` file.
For example:
2020-09-04 11:08:46 -04:00
```javascript
import { __ , s__ } from '~/locale';
const label = __ ('Subscribe');
const nameSpacedlabel = __ ('Plan|Subscribe');
```
For the static text strings we suggest two patterns for using these translations in Vue files:
- External constants file:
```javascript
javascripts
│
└───alert_settings
│ │ constants.js
│ └───components
│ │ alert_settings_form.vue
// constants.js
import { s__ } from '~/locale';
/* Integration constants */
export const I18N_ALERT_SETTINGS_FORM = {
saveBtnLabel: __ ('Save changes'),
};
// alert_settings_form.vue
import {
I18N_ALERT_SETTINGS_FORM,
} from '../constants';
< script >
export default {
i18n: {
I18N_ALERT_SETTINGS_FORM,
}
}
< / script >
< template >
< gl-button
ref="submitBtn"
variant="success"
type="submit"
>
{{ $options.i18n.I18N_ALERT_SETTINGS_FORM }}
< / gl-button >
< / template >
```
When possible, you should opt for this pattern, as this allows you to import these strings directly into your component specs for re-use during testing.
2020-10-08 14:08:32 -04:00
- Internal component `$options` object:
2020-09-04 11:08:46 -04:00
```javascript
< script >
export default {
2020-09-15 20:09:37 -04:00
i18n: {
2020-09-04 11:08:46 -04:00
buttonLabel: s__('Plan|Button Label')
}
},
< / script >
< template >
< gl-button :aria-label = "$options.i18n.buttonLabel" >
{{ $options.i18n.buttonLabel }}
< / gl-button >
< / template >
```
2021-06-08 17:10:05 -04:00
To visually test the Vue translations:
2017-10-24 00:16:57 -04:00
2021-06-08 17:10:05 -04:00
1. Change the GitLab localization to another language than English.
1. Generate JSON files using `bin/rake gettext:po_to_json` or `bin/rake gettext:compile` .
2017-10-24 00:16:57 -04:00
2021-06-08 17:10:05 -04:00
### Dynamic translations
2017-10-24 00:16:57 -04:00
2021-06-08 17:10:05 -04:00
Sometimes there are dynamic translations that the parser can't find when running
`bin/rake gettext:find` . For these scenarios you can use the [`N_` method ](https://github.com/grosser/gettext_i18n_rails/blob/c09e38d481e0899ca7d3fc01786834fa8e7aab97/Readme.md#unfound-translations-with-rake-gettextfind ).
There's also an alternative method to [translate messages from validation errors ](https://github.com/grosser/gettext_i18n_rails/blob/c09e38d481e0899ca7d3fc01786834fa8e7aab97/Readme.md#option-a ).
2017-10-24 00:16:57 -04:00
2018-02-15 12:17:13 -05:00
## Working with special content
2017-05-16 14:26:12 -04:00
### Interpolation
2021-06-08 17:10:05 -04:00
Placeholders in translated text should match the respective source file's code style. For example
use `%{created_at}` in Ruby but `%{createdAt}` in JavaScript. Make sure to
[avoid splitting sentences when adding links ](#avoid-splitting-sentences-when-adding-links ).
2018-01-25 08:36:04 -05:00
2017-05-16 14:26:12 -04:00
- In Ruby/HAML:
2019-07-31 04:28:51 -04:00
```ruby
_("Hello %{name}") % { name: 'Joe' } => 'Hello Joe'
```
2017-05-16 14:26:12 -04:00
2020-01-28 04:09:06 -05:00
- In Vue:
2021-03-18 11:09:04 -04:00
Use the [`GlSprintf` ](https://gitlab-org.gitlab.io/gitlab-ui/?path=/docs/utilities-sprintf--sentence-with-link ) component if:
2021-04-05 17:09:19 -04:00
2021-06-08 17:10:05 -04:00
- You need to include child components in the translation string.
- You need to include HTML in your translation string.
- You're using `sprintf` and need to pass `false` as the third argument to
2021-03-18 11:09:04 -04:00
prevent it from escaping placeholder values.
For example:
```html
< gl-sprintf :message = "s__('ClusterIntegration|Learn more about %{linkStart}zones%{linkEnd}')" >
< template #link ="{ content }" >
< gl-link :href = "somePath" > {{ content }}< / gl-link >
< / template >
< / gl-sprintf >
```
2021-06-08 17:10:05 -04:00
In other cases, it might be simpler to use `sprintf` , perhaps in a computed
2021-03-18 11:09:04 -04:00
property. For example:
```html
< script >
import { __ , sprintf } from '~/locale';
export default {
...
computed: {
userWelcome() {
sprintf(__('Hello %{username}'), { username: this.user.name });
}
}
...
}
< / script >
< template >
< span > {{ userWelcome }}< / span >
< / template >
```
2020-01-28 04:09:06 -05:00
- In JavaScript (when Vue cannot be used):
2017-10-24 00:16:57 -04:00
2020-05-19 14:08:11 -04:00
```javascript
2019-07-31 04:28:51 -04:00
import { __ , sprintf } from '~/locale';
2018-01-25 08:36:04 -05:00
2019-07-31 04:28:51 -04:00
sprintf(__('Hello %{username}'), { username: 'Joe' }); // => 'Hello Joe'
```
2017-05-16 14:26:12 -04:00
2021-03-18 11:09:04 -04:00
If you need to use markup within the translation, use `sprintf` and stop it
from escaping placeholder values by passing `false` as its third argument.
You **must** escape any interpolated dynamic values yourself, for instance
using `escape` from `lodash` .
2018-01-25 08:36:04 -05:00
2020-05-19 14:08:11 -04:00
```javascript
2020-01-28 04:09:06 -05:00
import { escape } from 'lodash';
2019-07-31 04:28:51 -04:00
import { __ , sprintf } from '~/locale';
2018-01-25 08:36:04 -05:00
2020-01-28 04:09:06 -05:00
let someDynamicValue = '< script > alert ( "evil" ) < / script > ';
// Dangerous:
sprintf(__('This is %{value}'), { value: `<strong>${someDynamicValue}</strong>` , false);
// => 'This is < strong > < script > alert ( 'evil' ) < / script > < / strong > '
// Incorrect:
sprintf(__('This is %{value}'), { value: `<strong>${someDynamicValue}</strong>` });
// => 'This is < strong> < script> alert(' evil' )< /script> < /strong> '
// OK:
2020-08-12 11:10:02 -04:00
sprintf(__('This is %{value}'), { value: `<strong>${escape(someDynamicValue)}</strong>` }, false);
2020-01-28 04:09:06 -05:00
// => 'This is < strong > < script> alert(' evil' )< /script> < / strong > '
2019-07-31 04:28:51 -04:00
```
2017-12-11 15:24:05 -05:00
2017-05-16 14:26:12 -04:00
### Plurals
- In Ruby/HAML:
2019-07-31 04:28:51 -04:00
```ruby
n_('Apple', 'Apples', 3)
# => 'Apples'
```
2017-05-16 14:26:12 -04:00
2019-07-31 04:28:51 -04:00
Using interpolation:
2017-05-16 14:26:12 -04:00
2019-07-31 04:28:51 -04:00
```ruby
n_("There is a mouse.", "There are %d mice.", size) % size
# => When size == 1: 'There is a mouse.'
# => When size == 2: 'There are 2 mice.'
```
2021-06-08 17:10:05 -04:00
Avoid using `%d` or count variables in singular strings. This allows more natural translation in
some languages.
2018-06-30 08:20:29 -04:00
2017-05-16 14:26:12 -04:00
- In JavaScript:
2020-05-19 14:08:11 -04:00
```javascript
2019-07-31 04:28:51 -04:00
n__('Apple', 'Apples', 3)
// => 'Apples'
```
2017-05-16 14:26:12 -04:00
2019-07-31 04:28:51 -04:00
Using interpolation:
2017-05-16 14:26:12 -04:00
2020-05-19 14:08:11 -04:00
```javascript
2019-07-31 04:28:51 -04:00
n__('Last day', 'Last %d days', x)
// => When x == 1: 'Last day'
// => When x == 2: 'Last 2 days'
```
2017-05-16 14:26:12 -04:00
2021-06-18 11:10:16 -04:00
The `n_` and `n__` methods should only be used to fetch pluralized translations of the same
2020-01-22 01:08:33 -05:00
string, not to control the logic of showing different strings for different
2021-06-08 17:10:05 -04:00
quantities. Some languages have different quantities of target plural forms.
For example, Chinese (simplified) has only one target plural form in our
translation tool. This means the translator has to choose to translate only one
of the strings, and the translation doesn't behave as intended in the other case.
2020-01-22 01:08:33 -05:00
2021-06-08 17:10:05 -04:00
For example, use this:
2020-01-22 01:08:33 -05:00
```ruby
if selected_projects.one?
selected_projects.first.name
else
2021-06-18 11:10:16 -04:00
n_("Project selected", "%d projects selected", selected_projects.count)
2020-01-22 01:08:33 -05:00
end
```
2021-06-08 17:10:05 -04:00
Instead of this:
2020-01-22 01:08:33 -05:00
```ruby
# incorrect usage example
n_("%{project_name}", "%d projects selected", count) % { project_name: 'GitLab' }
```
2017-05-16 14:26:12 -04:00
### Namespaces
2021-06-08 17:10:05 -04:00
A namespace is a way to group translations that belong together. They provide context to our
translators by adding a prefix followed by the bar symbol (`|`). For example:
2020-05-25 14:08:35 -04:00
```ruby
2020-06-05 11:08:23 -04:00
'Namespace|Translated string'
2020-05-25 14:08:35 -04:00
```
2021-06-08 17:10:05 -04:00
A namespace:
2020-05-25 14:08:35 -04:00
2021-06-08 17:10:05 -04:00
- Addresses ambiguity in words. For example: `Promotions|Promote` vs `Epic|Promote` .
- Allows translators to focus on translating externalized strings that belong to the same product
area, rather than arbitrary ones.
- Gives a linguistic context to help the translator.
2020-05-25 14:08:35 -04:00
2021-06-08 17:10:05 -04:00
In some cases, namespaces don't make sense. For example, for ubiquitous UI words and phrases such as
"Cancel" or phrases like "Save changes," a namespace could be counterproductive.
2020-05-25 14:08:35 -04:00
2019-05-23 04:11:28 -04:00
Namespaces should be PascalCase.
2017-05-16 14:26:12 -04:00
- In Ruby/HAML:
2019-07-31 04:28:51 -04:00
```ruby
s_('OpenedNDaysAgo|Opened')
```
2017-05-16 14:26:12 -04:00
2021-06-08 17:10:05 -04:00
If the translation isn't found, `Opened` is returned.
2017-05-16 14:26:12 -04:00
- In JavaScript:
2020-05-19 14:08:11 -04:00
```javascript
2019-07-31 04:28:51 -04:00
s__('OpenedNDaysAgo|Opened')
```
2017-05-16 14:26:12 -04:00
2021-06-08 17:10:05 -04:00
The namespace should be removed from the translation. For more details, see the
[translation guidelines ](translation.md#namespaced-strings ).
2018-02-15 12:17:13 -05:00
2020-07-22 08:09:42 -04:00
### HTML
2021-06-08 17:10:05 -04:00
We no longer include HTML directly in the strings that are submitted for translation. This is
because:
2020-07-22 08:09:42 -04:00
2021-06-08 17:10:05 -04:00
1. The translated string can accidentally include invalid HTML.
1. Translated strings can become an attack vector for XSS, as noted by the
2020-07-22 08:09:42 -04:00
[Open Web Application Security Project (OWASP) ](https://owasp.org/www-community/attacks/xss/ ).
2021-06-08 17:10:05 -04:00
To include formatting in the translated string, you can do the following:
2020-07-22 08:09:42 -04:00
- In Ruby/HAML:
```ruby
html_escape(_('Some %{strongOpen}bold%{strongClose} text.')) % { strongOpen: '< strong > '.html_safe, strongClose: '< / strong > '.html_safe }
# => 'Some < strong > bold< / strong > text.'
```
- In JavaScript:
```javascript
sprintf(__('Some %{strongOpen}bold%{strongClose} text.'), { strongOpen: '< strong > ', strongClose: '< / strong > '}, false);
// => 'Some < strong > bold< / strong > text.'
```
2021-06-08 17:10:05 -04:00
- In Vue:
2020-07-22 08:09:42 -04:00
See the section on [interpolation ](#interpolation ).
2021-06-08 17:10:05 -04:00
When [this translation helper issue ](https://gitlab.com/gitlab-org/gitlab/-/issues/217935 )
is complete, we plan to update the process of including formatting in translated strings.
2020-07-22 08:09:42 -04:00
#### Including Angle Brackets
2021-06-08 17:10:05 -04:00
If a string contains angle brackets (`< `/`>`) that are not used for HTML, the `rake gettext:lint`
linter still flags it. To avoid this error, use the applicable HTML entity code (`< ` or `>` )
instead:
2020-07-22 08:09:42 -04:00
- In Ruby/HAML:
```ruby
html_escape_once(_('In < 1 hour')).html_safe
# => 'In < 1 hour '
```
- In JavaScript:
```javascript
2020-09-23 02:09:45 -04:00
import { sanitize } from '~/lib/dompurify';
2020-07-22 08:09:42 -04:00
2020-08-24 20:10:16 -04:00
const i18n = { LESS_THAN_ONE_HOUR: sanitize(__('In < 1 hour'), { ALLOWED_TAGS: [] }) };
2020-07-22 08:09:42 -04:00
// ... using the string
element.innerHTML = i18n.LESS_THAN_ONE_HOUR;
// => 'In < 1 hour '
```
- In Vue:
```vue
< gl-sprintf :message = "s__('In < 1 hours')" / >
// => 'In < 1 hour '
```
2021-05-07 08:10:27 -04:00
### Numbers
2021-06-08 17:10:05 -04:00
Different locales may use different number formats. To support localization of numbers, we use
`formatNumber` , which leverages [`toLocaleString()` ](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString ).
2021-05-07 08:10:27 -04:00
2021-06-08 17:10:05 -04:00
By default, `formatNumber` formats numbers as strings using the current user locale.
2021-05-07 08:10:27 -04:00
2021-06-08 17:10:05 -04:00
- In JavaScript:
2021-05-07 08:10:27 -04:00
```javascript
import { formatNumber } from '~/locale';
// Assuming "User Preferences > Language" is set to "English":
const tenThousand = formatNumber(10000); // "10,000" (uses comma as decimal symbol in English locale)
const fiftyPercent = formatNumber(0.5, { style: 'percent' }) // "50%" (other options are passed to toLocaleString)
```
2021-06-08 17:10:05 -04:00
- In Vue templates:
2021-05-07 08:10:27 -04:00
```html
< script >
import { formatNumber } from '~/locale';
export default {
//...
methods: {
// ...
formatNumber,
},
}
< / script >
< template >
< div class = "my-number" >
{{ formatNumber(10000) }} <!-- 10,000 -->
< / div >
< div class = "my-percent" >
{{ formatNumber(0.5, { style: 'percent' }) }} <!-- 50% -->
< / div >
< / template >
```
2017-12-11 07:25:49 -05:00
### Dates / times
- In JavaScript:
2020-05-19 14:08:11 -04:00
```javascript
2018-02-15 12:17:13 -05:00
import { createDateTimeFormat } from '~/locale';
2017-12-11 07:25:49 -05:00
const dateFormat = createDateTimeFormat({ year: 'numeric', month: 'long', day: 'numeric' });
console.log(dateFormat.format(new Date('2063-04-05'))) // April 5, 2063
```
2020-06-04 17:08:11 -04:00
This makes use of [`Intl.DateTimeFormat` ](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat ).
2017-12-11 07:25:49 -05:00
2021-06-08 17:10:05 -04:00
- In Ruby/HAML, there are two ways of adding format to dates and times:
2019-01-22 18:59:01 -05:00
2021-06-08 17:10:05 -04:00
- **Using the `l` helper**: for example, `l(active_session.created_at, format: :short)` . We have
some predefined formats for [dates ](https://gitlab.com/gitlab-org/gitlab/-/blob/4ab54c2233e91f60a80e5b6fa2181e6899fdcc3e/config/locales/en.yml#L54 )
and [times ](https://gitlab.com/gitlab-org/gitlab/-/blob/4ab54c2233e91f60a80e5b6fa2181e6899fdcc3e/config/locales/en.yml#L262 ).
If you need to add a new format, because other parts of the code could benefit from it, add it
to the file [`en.yml` ](https://gitlab.com/gitlab-org/gitlab/-/blob/master/config/locales/en.yml ).
- **Using `strftime` **: for example, `milestone.start_date.strftime('%b %-d')` . We use `strftime`
in case none of the formats defined in [`en.yml` ](https://gitlab.com/gitlab-org/gitlab/-/blob/master/config/locales/en.yml )
match the date/time specifications we need, and if there's no need to add it as a new format
because it's very particular (for example, it's only used in a single view).
2019-01-22 18:59:01 -05:00
2018-02-15 12:17:13 -05:00
## Best practices
2020-11-09 13:09:11 -05:00
### Minimize translation updates
2021-06-08 17:10:05 -04:00
Updates can result in the loss of the translations for this string. To minimize risks, avoid changes
to strings unless they:
2020-11-09 13:09:11 -05:00
2021-06-08 17:10:05 -04:00
- Add value for the user.
2020-11-09 13:09:11 -05:00
- Include extra context for translators.
2021-06-08 17:10:05 -04:00
For example, avoid changes like this:
2020-11-09 13:09:11 -05:00
```diff
- _('Number of things: %{count}') % { count: 10 }
+ n_('Number of things: %d', 10)
```
2020-04-21 11:21:10 -04:00
### Keep translations dynamic
There are cases when it makes sense to keep translations together within an array or a hash.
Examples:
- Mappings for a dropdown list
- Error messages
2021-06-08 17:10:05 -04:00
To store these kinds of data, using a constant seems like the best choice. However, this doesn't
work for translations.
2020-04-21 11:21:10 -04:00
2021-06-08 17:10:05 -04:00
For example, avoid this:
2020-04-21 11:21:10 -04:00
```ruby
class MyPresenter
MY_LIST = {
key_1: _('item 1'),
key_2: _('item 2'),
key_3: _('item 3')
}
end
```
2021-06-08 17:10:05 -04:00
The translation method (`_`) is called when the class loads for the first time and translates the
text to the default locale. Regardless of the user's locale, these values are not translated a
second time.
2020-04-21 11:21:10 -04:00
2021-06-08 17:10:05 -04:00
A similar thing happens when using class methods with memoization.
2020-04-21 11:21:10 -04:00
2021-06-08 17:10:05 -04:00
For example, avoid this:
2020-04-21 11:21:10 -04:00
```ruby
class MyModel
def self.list
@list ||= {
key_1: _('item 1'),
key_2: _('item 2'),
key_3: _('item 3')
}
end
end
```
2021-06-08 17:10:05 -04:00
This method memoizes the translations using the locale of the user who first called this method.
2020-04-21 11:21:10 -04:00
To avoid these problems, keep the translations dynamic.
Good:
```ruby
class MyPresenter
def self.my_list
{
key_1: _('item 1'),
key_2: _('item 2'),
key_3: _('item 3')
}.freeze
end
end
```
2018-02-15 12:17:13 -05:00
### Splitting sentences
2021-06-08 17:10:05 -04:00
Never split a sentence, as it assumes the sentence's grammar and structure is the same in all
languages.
2018-02-15 12:17:13 -05:00
2021-06-08 17:10:05 -04:00
For example, this:
2018-02-15 12:17:13 -05:00
2020-05-19 14:08:11 -04:00
```javascript
2018-02-15 12:17:13 -05:00
{{ s__("mrWidget|Set by") }}
2018-02-28 12:47:02 -05:00
{{ author.name }}
2018-02-15 12:17:13 -05:00
{{ s__("mrWidget|to be merged automatically when the pipeline succeeds") }}
```
2021-06-08 17:10:05 -04:00
Should be externalized as follows:
2018-02-15 12:17:13 -05:00
2020-05-19 14:08:11 -04:00
```javascript
2018-02-28 12:47:02 -05:00
{{ sprintf(s__("mrWidget|Set by %{author} to be merged automatically when the pipeline succeeds"), { author: author.name }) }}
2018-02-15 12:17:13 -05:00
```
2018-06-12 08:29:52 -04:00
#### Avoid splitting sentences when adding links
2021-06-08 17:10:05 -04:00
This also applies when using links in between translated sentences. Otherwise, these texts are not
translatable in certain languages.
2018-06-12 08:29:52 -04:00
2019-06-27 22:54:22 -04:00
- In Ruby/HAML, instead of:
2019-07-31 04:28:51 -04:00
```haml
- zones_link = link_to(s_('ClusterIntegration|zones'), 'https://cloud.google.com/compute/docs/regions-zones/regions-zones', target: '_blank', rel: 'noopener noreferrer')
= s_('ClusterIntegration|Learn more about %{zones_link}').html_safe % { zones_link: zones_link }
```
2021-06-08 17:10:05 -04:00
Set the link starting and ending HTML fragments as variables:
2019-07-31 04:28:51 -04:00
```haml
- zones_link_url = 'https://cloud.google.com/compute/docs/regions-zones/regions-zones'
- zones_link_start = '< a href = "%{url}" target = "_blank" rel = "noopener noreferrer" > '.html_safe % { url: zones_link_url }
2021-03-31 08:08:55 -04:00
= html_escape(s_('ClusterIntegration|Learn more about %{zones_link_start}zones%{zones_link_end}')) % { zones_link_start: zones_link_start, zones_link_end: '< / a > '.html_safe }
2019-07-31 04:28:51 -04:00
```
2018-06-12 08:29:52 -04:00
2020-01-28 04:09:06 -05:00
- In Vue, instead of:
```html
< template >
< div >
< gl-sprintf :message = "s__('ClusterIntegration|Learn more about %{link}')" >
< template #link >
< gl-link
href="https://cloud.google.com/compute/docs/regions-zones/regions-zones"
target="_blank"
>zones< / gl-link >
< / template >
< / gl-sprintf >
< / div >
< / template >
```
2021-06-08 17:10:05 -04:00
Set the link starting and ending HTML fragments as placeholders:
2020-01-28 04:09:06 -05:00
```html
< template >
< div >
< gl-sprintf :message = "s__('ClusterIntegration|Learn more about %{linkStart}zones%{linkEnd}')" >
< template #link ="{ content }" >
< gl-link
href="https://cloud.google.com/compute/docs/regions-zones/regions-zones"
target="_blank"
>{{ content }}< / gl-link >
< / template >
< / gl-sprintf >
< / div >
< / template >
```
- In JavaScript (when Vue cannot be used), instead of:
2018-06-12 08:29:52 -04:00
2020-05-19 14:08:11 -04:00
```javascript
2019-07-31 04:28:51 -04:00
{{
sprintf(s__("ClusterIntegration|Learn more about %{link}"), {
link: '< a href = "https://cloud.google.com/compute/docs/regions-zones/regions-zones" target = "_blank" rel = "noopener noreferrer" > zones< / a > '
2021-03-18 11:09:04 -04:00
}, false)
2019-07-31 04:28:51 -04:00
}}
```
2021-06-08 17:10:05 -04:00
Set the link starting and ending HTML fragments as placeholders:
2019-07-31 04:28:51 -04:00
2020-05-19 14:08:11 -04:00
```javascript
2019-07-31 04:28:51 -04:00
{{
sprintf(s__("ClusterIntegration|Learn more about %{linkStart}zones%{linkEnd}"), {
2020-01-24 04:08:32 -05:00
linkStart: '< a href = "https://cloud.google.com/compute/docs/regions-zones/regions-zones" target = "_blank" rel = "noopener noreferrer" > ',
2019-07-31 04:28:51 -04:00
linkEnd: '< / a > ',
2021-03-18 11:09:04 -04:00
}, false)
2019-07-31 04:28:51 -04:00
}}
```
2018-06-12 08:29:52 -04:00
2021-06-08 17:10:05 -04:00
The reasoning behind this is that in some languages words change depending on context. For example,
in Japanese は is added to the subject of a sentence and を to the object. This is impossible to
translate correctly if you extract individual words from the sentence.
2018-06-12 08:29:52 -04:00
2021-06-08 17:10:05 -04:00
When in doubt, try to follow the best practices described in this [Mozilla Developer documentation ](https://developer.mozilla.org/en-US/docs/Mozilla/Localization/Localization_content_best_practices#Splitting ).
2018-02-15 12:17:13 -05:00
## Updating the PO files with the new content
2021-06-08 17:10:05 -04:00
Now that the new content is marked for translation, run this command to update the
`locale/gitlab.pot` files:
2018-02-15 12:17:13 -05:00
2020-01-30 10:09:15 -05:00
```shell
2018-07-06 08:40:23 -04:00
bin/rake gettext:regenerate
2018-02-15 12:17:13 -05:00
```
2021-06-08 17:10:05 -04:00
This command updates the `locale/gitlab.pot` file with the newly externalized strings and removes
any unused strings. Once the changes are on the default branch, [CrowdIn ](https://translate.gitlab.com )
picks them up and presents them for translation.
2019-09-24 23:06:21 -04:00
2021-06-08 17:10:05 -04:00
You don't need to check in any changes to the `locale/[language]/gitlab.po` files. They are updated
automatically when [translations from CrowdIn are merged ](merging_translations.md ).
2018-02-15 12:17:13 -05:00
2021-06-08 17:10:05 -04:00
If there are merge conflicts in the `gitlab.pot` file, you can delete the file and regenerate it
using the same command.
2018-02-15 12:17:13 -05:00
### Validating PO files
2021-06-08 17:10:05 -04:00
To make sure we keep our translation files up to date, there's a linter that runs on CI as part of
the `static-analysis` job. To lint the adjustments in PO files locally, you can run
`rake gettext:lint` .
2018-02-15 12:17:13 -05:00
2020-12-07 13:10:36 -05:00
The linter takes the following into account:
2018-02-15 12:17:13 -05:00
2021-06-08 17:10:05 -04:00
- Valid PO-file syntax.
- Variable usage.
- Only one unnamed (`%d`) variable, since the order of variables might change in different
languages.
- All variables used in the message ID are used in the translation.
- There should be no variables used in a translation that aren't in the message ID.
2018-02-15 12:17:13 -05:00
- Errors during translation.
2021-06-08 17:10:05 -04:00
- Presence of angle brackets (`< ` or `>` ).
2018-02-15 12:17:13 -05:00
The errors are grouped per file, and per message ID:
2020-03-25 02:07:58 -04:00
```plaintext
2018-02-15 12:17:13 -05:00
Errors in `locale/zh_HK/gitlab.po` :
PO-syntax errors
SimplePoParser::ParserErrorSyntax error in lines
Syntax error in msgctxt
Syntax error in msgid
Syntax error in msgstr
Syntax error in message_line
There should be only whitespace until the end of line after the double quote character of a message text.
2020-08-12 17:09:54 -04:00
Parsing result before error: '{:msgid=>["", "You are going to delete %{project_name_with_namespace}.\\n", "Deleted projects CANNOT be restored!\\n", "Are you ABSOLUTELY sure?"]}'
2018-02-15 12:17:13 -05:00
SimplePoParser filtered backtrace: SimplePoParser::ParserError
Errors in `locale/zh_TW/gitlab.po` :
1 pipeline
< %d 條流水線> is using unknown variables: [%d]
Failure translating to zh_TW with []: too few arguments
```
2021-06-08 17:10:05 -04:00
In this output, `locale/zh_HK/gitlab.po` has syntax errors. The file `locale/zh_TW/gitlab.po` has
variables in the translation that aren't in the message with ID `1 pipeline` .
2018-02-15 12:17:13 -05:00
2017-05-16 14:26:12 -04:00
## Adding a new language
2021-05-14 14:10:34 -04:00
A new language should only be added as an option in User Preferences once at least 10% of the
strings have been translated and approved. Even though a larger number of strings may have been
translated, only the approved translations display in the GitLab UI.
2020-12-04 16:09:29 -05:00
NOTE:
2020-07-31 17:10:12 -04:00
[Introduced ](https://gitlab.com/gitlab-org/gitlab/-/issues/221012 ) in GitLab 13.3:
2020-12-07 13:10:36 -05:00
Languages with less than 2% of translations are not available in the UI.
2020-07-31 17:10:12 -04:00
2021-06-08 17:10:05 -04:00
Suppose you want to add translations for a new language, for example, French:
2017-05-16 14:26:12 -04:00
2021-06-08 17:10:05 -04:00
1. Register the new language in `lib/gitlab/i18n.rb` :
2017-05-16 14:26:12 -04:00
2019-07-31 04:28:51 -04:00
```ruby
...
AVAILABLE_LANGUAGES = {
...,
'fr' => 'Français'
}.freeze
...
```
2017-05-16 14:26:12 -04:00
2021-06-08 17:10:05 -04:00
1. Add the language:
2017-05-16 14:26:12 -04:00
2020-01-30 10:09:15 -05:00
```shell
2019-07-31 04:28:51 -04:00
bin/rake gettext:add_language[fr]
```
2017-05-16 14:26:12 -04:00
2021-06-08 17:10:05 -04:00
If you want to add a new language for a specific region, the command is similar. You must
separate the region with an underscore (`_`), specify the region in capital letters. For example:
2017-05-16 14:26:12 -04:00
2020-01-30 10:09:15 -05:00
```shell
2019-07-31 04:28:51 -04:00
bin/rake gettext:add_language[en_GB]
```
2017-05-16 14:26:12 -04:00
2021-06-08 17:10:05 -04:00
1. Adding the language also creates a new directory at the path `locale/fr/` . You can now start
using your PO editor to edit the PO file located at `locale/fr/gitlab.edit.po` .
2017-05-16 14:26:12 -04:00
2021-06-08 17:10:05 -04:00
1. After updating the translations, you must process the PO files to generate the binary MO files,
and update the JSON files containing the translations:
2017-05-16 14:26:12 -04:00
2020-01-30 10:09:15 -05:00
```shell
2019-07-31 04:28:51 -04:00
bin/rake gettext:compile
```
2017-05-16 14:26:12 -04:00
2021-06-08 17:10:05 -04:00
1. To see the translated content, you must change your preferred language. You can find this under
the user's **Settings** (`/profile`).
2017-05-16 14:26:12 -04:00
2021-06-08 17:10:05 -04:00
1. After checking that the changes are ok, commit the new files. For example:
2017-05-16 14:26:12 -04:00
2020-01-30 10:09:15 -05:00
```shell
2019-07-31 04:28:51 -04:00
git add locale/fr/ app/assets/javascripts/locale/fr/
2020-02-07 16:08:39 -05:00
git commit -m "Add French translations for Value Stream Analytics page"
2019-07-31 04:28:51 -04:00
```