---
url: /everyone/internationalization.md
---
# Internationalization

## Translator's Guide

Open Library's interface is translated on **Weblate**, a website for translating software. You do not need GitHub, git or a local setup.

1. Go to [openlibrary.org/translate](https://openlibrary.org/translate). It takes you to the Open Library project on Weblate.
2. [Create an account](https://translate.archive.org/accounts/register/), or sign in.
3. Pick your language and start translating. Weblate shows each English string, where it is used, and any translator notes.

When you save, Weblate sends your work to the [`openlibrary-i18n`](https://github.com/internetarchive/openlibrary-i18n) repository, where it is merged automatically after an automated check for abuse and broken formatting. It reaches openlibrary.org after the next base-image build and deploy. That is usually within a week.

### How translations get made

Most strings are first translated by AI. Whenever the English strings change, an automated job fills in the untranslated strings in every language. **Human translators correct and improve them.** Fixing an awkward or wrong AI translation is just as useful as translating a new string.

### Tips

* Keep placeholders exactly as they are, for example `%(count)d` or `%(name)s`. You may move them within the sentence.
* Keep HTML tags such as `<a href="...">` and `<strong>` as they are. Translate only the text inside them.
* Translate the whole sentence so it reads naturally in your language. You do not have to keep the English word order.
* Plural strings have one box per plural form of your language. Fill in every form.
* If a string cannot be translated correctly, for example because the code joins sentence fragments together, [open an issue](https://github.com/internetarchive/openlibrary/issues/new/choose) that says where the string is and what the problem is.

To see the site in your language, add `?lang=` and the language code to any URL, for example <https://openlibrary.org/?lang=fr>, or [set your browser's language preferences](https://www.w3.org/International/questions/qa-lang-priorities).

### Adding a new language

[Open an issue in `openlibrary-i18n`](https://github.com/internetarchive/openlibrary-i18n/issues) to ask for the language. Once it is set up, it appears on Weblate. For it to appear in the site's language menu, a developer also adds it to `get_supported_languages()` in [`openlibrary/plugins/openlibrary/code.py`](https://github.com/internetarchive/openlibrary/blob/master/openlibrary/plugins/openlibrary/code.py).

### Editing `.po` files directly

If you prefer to work with files, edit `locale/<lang>/messages.po` in [`openlibrary-i18n`](https://github.com/internetarchive/openlibrary-i18n) and open a pull request against `main`. Its [README](https://github.com/internetarchive/openlibrary-i18n#contributing-translations) explains how to run the checks first.

**Do not edit the `.po` files in the main `openlibrary` repository.** They are overwritten with the `openlibrary-i18n` files every time the site is built, so changes there are lost.

### Glossary

* `.pot` (Portable Object Template): the list of every English string in Open Library, before translation.
* `.po` (Portable Object): one language's translations of those strings. This is what Weblate edits.
* `.mo` (Machine Object): the compiled form of a `.po` file that the site reads. It is built automatically.

## Internationalization (i18n) Developer's Guide

Any text that will be visible to the user should be internationalized. This section covers Templetor (`.html`), Python and JavaScript. For Jinja templates (`.html.jinja`), see the [Jinja guide](/developers/frontend/jinja.md) and the [i18n guide in the main repository](https://github.com/internetarchive/openlibrary/blob/master/docs/i18n/i18n.md). For how translations are stored and shipped, see the [i18n pipeline doc](https://github.com/internetarchive/openlibrary/blob/master/docs/i18n/i18n-pipeline.md).

### Updating `messages.pot`

When you add or change a user-visible string, the `generate-pot` [pre-commit](/developers/tools/pre-commit.md) hook regenerates `openlibrary/i18n/messages.pot`. Commit that file with your change. To regenerate it by hand, run:

```sh
docker compose run --rm -uroot home ./scripts/i18n-messages extract
```

After your PR is merged, the new strings are translated automatically and then show up on Weblate for review. You never need to edit a `.po` file yourself.

The basics of web.py's `templetor` i18n support are described in the [web.py i18n support in template files cookbook](http://webpy.org/cookbook/i18n_support_in_template_file).

The two primary i18n message functions are:

* `gettext()` which is bound to '\_' as a convenience since it's commonly used
* `ngettext()` (or `ungettext()` as we've historically used) which currently needs to be spelled out, but is commonly bound to `N_`, so that's a convention we may adopt.

## HTML Files

| Text Type                           | Example Text                                                                                         | Example Syntax                                                                                                                              | Notes                                                                                                                                                                                                                                                                                         |
| ----------------------------------- | ---------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Plain inner HTML                    | `<p>About this book:</p>`                                                                            | `<p>$_("About this book:")</p>`                                                                                                             | Wrap it in `$_(" ")`                                                                                                                                                                                                                                                                          |
| `title` or `alt` attributes         | `<button title="Submit" alt="Submit button">`                                                        | `<button title="$_('Submit')" alt="$_('Submit button')">`                                                                                   | Wrap it in `$_(' ')` - note the use of single quotes                                                                                                                                                                                                                                          |
| `value` attributes                  | `<button value="Submit" />` or `<input value="Enter your name"`                                      | `<button value="$_('Submit')" />` & `<input value="$_('Enter your name...')"`                                                               | **Note:** You only need to use the `i18n` syntax if the `value` is being used to set visible placeholder text -- `value`s like this one can be left as is: `<button value="add">$_("Add")</button>`                                                                                           |
| Text that contains `'` or `"`       | `title="That's strange!"` or `<p>Click "Add"</p>`                                                    | `title="$_('That\'s strange!')"` or `<p>$_("Click \"Add\"")</p>`                                                                            | If there's a conflict between the outer and inner quotes, i.e. `'` or `""` inside `"$_(' ')"` or `""` inside `$_(" ")`, escape the inner quote/apostrophe with a `\`                                                                                                                          |
| Text that contains a variable       | `title="Photo of $author_name"`                                                                      | `title="$_('Photo of %(author)s', author=author_name)`                                                                                      | Wrap a stand-in for the variable in `%( )s` if the variable is a string, or `%( )d` if the variable is a number, and then assign your stand-in to the initial variable; **Note**: It's important to use a meaningful stand-in name here, like "count" or "author" to give translators context |
| Text that contains nested HTML tags | `<p>Would you like to <strong>return</strong>?</p>`                                                  | `<p>$:_('Would you like to <strong>return</strong>?')</p>`                                                                                  | Wrap each full sentence and punctuation in `$:_(' ')` -- note the `:` and single quotes\*                                                                                                                                                                                                     |
| Text that contains a plural         | `("There is one person waiting for this book.", "There are {wlsize} people waiting for this book.")` | `$ungettext("There is %(count)d person waiting for this book.", "There are %(count)d people waiting for this book.", wlsize, count=wlsize)` | Write out `ungettext` instead of the traditional `_` and sub in the variable (see variable instructions)\*\*                                                                                                                                                                                  |

Everything enclosed within any version of the `$_(' ')` syntax will be extracted into messages.pot file. Review the [messages.pot](https://github.com/internetarchive/openlibrary/blob/master/openlibrary/i18n/messages.pot) file to get an idea of what the extracted messages look like.

When syntaxing messages that are split up by nested HTML tags, consider if the message can be translated in chunks, or if the meaning of the chunks depends on the sentence as a whole. If it can be broken into chunks, it will save the translators the effort (and potential risk) of copy & pasting HTML. However, translation accuracy is the priority.

**Note**:

* There's no need to do nested `i18n`, i.e. the `title` in `$:_('Click <a href="$link" title="External Link">Here</a>')` would already be translated with the rest of the string.
* Be sure to include punctuation marks inside parentheses, i.e. the `.` at the end of `>$:_(' Please read our <a href="/help/faq">FAQ</a>.')`
* Exclude HTML syntax where possible to avoid unnecessary copy and pasting for translators, i.e. you can leave out the `&nbsp;` here like so: `&nbsp;&nbsp;$_("Add some subjects")`
* *But* if you include an HTML closing tag, be sure to include the opening tag as well, i.e. `$:_('<strong>Download the DAISY.zip</strong>.)`
* While working, avoid moving extra spaces to the beginning or end `<a></a>` tags, which will cause weird links that look like[this](#internationalization)
* You may run across some untranslated HTML in the JavaScript test files; this is fine, and should be left as is

### Enforcement

Non-compliant HTML changes will be flagged by the `detect_missing_i18n` pre-commit script and fail CI. To see all affected lines locally, [install pre-commit](https://pre-commit.com/) and run `pre-commit run detect-missing-i18n`. See the [Pre-Commit Guide](/developers/tools/pre-commit.md) for more information.

If the i18n error or warning is a false positive, you may append `$# detect-missing-i18n-skip-line` to the end of your line ([example](https://github.com/internetarchive/openlibrary/pull/9428/files#diff-bca2a6fdc75087bace987c1ffb52482a8aa9777a653f9f5b18971218cf8638eaR35)). You may also insert a line above the detected error that only contains `$# detect-missing-i18n-skip-line` ([example](https://github.com/internetarchive/openlibrary/pull/9428/files#diff-bcf3ac61effa00d5a5e5e195cf8be38f6e11d3949e56d4474dd236c89bb01ae4R255)).

Do not add your file to the `EXCLUDE_LIST` array within the `detect_missing_i18n` script. This list is intended only for files that had existing errors at the time the pre-commit check was created, and these errors will be addressed and taken out of the list over time.

***

\* You should try to avoid this where possible because it requires the translator to copy the HTML exactly—but sometimes you can't avoid it. Note you *should not* split up the sentence; it might not make sense in other languages.

These sentences however *can* be represented without i18n-ing the HTML by using python template strings:

```html
$def cc0_link():
<a
  href="https://creativecommons.org/publicdomain/zero/1.0/"
  target="_blank"
  title="$_('This link to Creative Commons will open in a new window')"
  >$_('CC0')</a
>

$:(_('By saving a change to this wiki, you agree that your contribution is given
freely to the world under %s. Yippee!') % str(cc0_link()).strip())
```

In this way, only the text is presented to the translators.

\*\* In the translation file, this would look like:

```po
#: borrow.html:114
#, python-format
msgid "There is %(count)d person waiting for this book."
msgid_plural "There are %(count)d people waiting for this book."
msgstr[0] "%(count)d personne attend ce livre."
msgstr[1] "%(count)d personnes attendent ce livre."
```

The top of the file declares the number of different plural forms for the language since this varies widely among languages.
There is more information in the [gettext manual section on plural forms](https://www.gnu.org/software/gettext/manual/html_node/Plural-forms.html).

## Python Files

* Follow the HTML instructions above, but omit the `$`. E.g.

```python
from openlibrary.i18n import gettext as _, ungettext

_('My translated string!')
```

**Note**:
When adding Python translations, you may encounter an `AttributeError` like `'ThreadedDict' object has no attribute 'lang'`.
This can happen if translated text is at the top of the file rather than nested in a function, as the `gettext` function `_` requires the language context (`web.ctx.lang`) to be ready before it runs.

A simple workaround for this problem is nesting the desired text inside a function, either directly where it will be used or as a helper function near the top of the file.

For instance, a dict like this:

```py
LOGIN_ERRORS = {
  "invalid_email": _("The email address you entered is invalid"),
  "account_blocked": _("This account has been blocked"),
  "account_locked": _("This account has been locked"),
  ...
}
```

can be made translation-safe if nested in a function like so:

```py
def get_login_error(error_key):
    LOGIN_ERRORS = {
        "invalid_email": _("The email address you entered is invalid"),
        "account_blocked": _("This account has been blocked"),
        "account_locked": _("This account has been locked"),
        ...
    }

    return LOGIN_ERRORS[error_key]
```

## JavaScript Files

Unlike our Python code and HTML templates, there is currently no way to extract strings from our Javascript code for localization. To bypass this limitation, we have been including localized strings in a `data-i18n` attribute.

As an example, the following code will display the localized `Hello World` message in the `.greeting-example` span when the `greeting.html` template is rendered on a page.

In the `greeting.html` template, we first create a `dict` that will contain all of the localized UI strings that will be used by the client-side code. In this case, we only have a single string.
This `dict` is then added to the root element of the template in a `data-i18n` attribute. The `json_encode` call simply converts a Python `dict` to a JSON string.

`/openlibrary/templates/greeting.html`:

```html
$def with () $ i18n_strings = { $ 'greeting': _('Hello World') $ }

<span class="greeting-example" data-i18n="$json_encode(i18n_strings)"></span>
```

In the main `index.js` file, we add code that initializes the `.greeting-example` element if it
exists on the page.

`js/index.js`:

```js
const greetingElement = document.querySelector(".greeting-example");
if (greetingElement) {
  import("greeting").then((module) => module.initGreeting(greetingElement));
}
```

In `initGreeting`, we parse the value of `data-i18n` and set the `textContent` of the greeting
span to the localized "Hello World" string.

`js/greeting.js`:

```js
/**
 * Sets text content of the given element to the localized greeting.
 *
 * @param {HTMLElement} greetingElement
 */
export function initGreeting(greetingElement) {
  const i18nStrings = JSON.parse(greetingElement.dataset.i18n);
  greetingElement.textContent = i18nStrings.greeting;
}
```

## Best Practices

**Must DOs**:

* Internationalize all user visible strings, including HTML `title` and `alt` which are used
* Use consistent terminology and phrasing throughout the UI to reduce the amount of text which needs to be translated
* Use meaningful mnemonic parameter names to help the translators understand the context. e.g. "%(editioncount)d editions"
* Double check that the format string types match the types of parameters being passed. Mismatches will cause errors at runtime.
* Be sure to escape embedded quotes and apostrophes, if necessary, after wrapping strings in single/double quotes. e.g. "\_$('Mustn't forget to escape')"
* Be sure to remove extra dollar signs ($) when wrapping expressions with $\_()
* Generate a message catalog template (messages.pot) when user visible strings are added or change
* Make changes incrementally in small batches. Multiple preprocessors (templator + babel) can make error messages obscure, so it's easier to debug if you know what changed.

**DON'Ts**:

* Don't display internal status / keyword values from the code directly to the user. These can't be internationalized.
* Don't do pluralization or string concatenation in code or templates. This mandates ordering in ways that can't be translated. Give the translators completed sentences or phrases, with embedded replacements, to work with so they can create natural translations.
* Don't use inline styling or links in text, if at all possible. e.g. `<em>`, `<a href=foo>`
* Don't edit the translated message catalogs (`.po` files). Translations live in [`openlibrary-i18n`](https://github.com/internetarchive/openlibrary-i18n) and are made by the AI job and by translators on Weblate. Do commit the updated template (`messages.pot`).
* Don't hard code in `1` for singular nouns (e.g. `1 edition`) because in some languages, `0 editions` is singular and translated as `0 edition`. Instead, substitute a variable, as you would with the plural. E.g. `$ungettext("There is %(count)d person waiting for this book.", "There are %(count)d people waiting for this book.", wlsize, count=wlsize)` and **not** `$ungettext("There is 1 person waiting for this book.", "There are %(count)d people waiting for this book.", wlsize, count=wlsize)`

## Internationalization (i18n) Page Conversion Guide

Internationalization (i18n) pages are specialized pages within the Infogami platform that enable users to contribute translations. This guide outlines the process of converting a standard page into an i18n page, using the example of converting <https://openlibrary.org/librarians> to its English (`en`) i18n version.

Follow these steps to convert a standard page into an i18n page. In this example, we'll use <https://openlibrary.org/librarians> as the source page to be converted into its English (`en`) i18n version.

### Prerequisites

1. Administrator permissions on the Infogami platform.

## Steps

1. **Create the English (`en`) Version of the Page**
   * Access the page: <https://openlibrary.org/librarians.en.yml?m=edit>
   * Copy the content from the unsuffixed page: <https://openlibrary.org/librarians.yml?m=edit>
   * Update the `key` field to include the `.en` suffix.
2. **Edit the Un-Suffixed Page**
   * Access the unsuffixed page: <https://openlibrary.org/librarians.yml?m=edit>
   * Remove the existing `body` content.
   * Change the `type` field to `/type/i18n_page`.
3. **Test**
   * Access <https://openlibrary.org/librarians> to ensure it displays content in English (or your desired locale).
   * Access <https://openlibrary.org/librarians?lang=es> to verify that it displays content in Spanish (or the corresponding locale).

This concludes the process of converting a standard page into an i18n page, making it accessible in multiple languages. Ensure that you have made the necessary updates to the `key` and `type` fields as specified above.

### Automating i18n page creation

@cdrini has a script to help automate the creation if i18n versions of openlibrary.org infogami pages (e.g. <https://openlibrary.org/about> v. <https://openlibrary.org/about.es>):

<https://gist.github.com/cdrini/615d75653e1e47115930fa394e83ab17>
