Fluent for Firefox Developers
Fluent is a modern localization system introduced into the Gecko platform with a focus on quality, performance, maintenance and completeness.
This document covers using Fluent for Firefox localization. For a more hands-on tutorial of understanding Fluent from the ground up, try following the Fluent DOMLocalization Tutorial, which provides some background on how Fluent works and walks you through creating a basic web project from scratch that uses Fluent for localization.
Why Use Fluent?
Fluent ties tightly into Unicode, CLDR and ICU, and keeps the complexity of each language in the translation, where localizers can deal with it, instead of leaking it into the source code. A single, declarative API based on DOM attributes is used to localize XUL, XHTML, HTML and Web Components, and the same messages are available to JavaScript, C++ and Rust code.
Getting Started
If you work on any patch that touches FTL files, you’ll need to get a review from fluent-reviewers. There’s a Herald hook that automatically sets that group as a blocking reviewer.
To minimize back-and-forth during the review, please take a moment to review some of the best practices above before submitting your patch for review.
Fluent Translation List - FTL
Fluent introduces a file format designed specifically for easy readability and the localization features offered by the system.
At first glance the format is a simple key-value store. It may look like this:
home-page-header = Home Page
# The label of a button opening a new tab
new-tab-open = Open New Tab
But the FTL file format is significantly more powerful and the additional features quickly add up. In order to familiarize yourself with the basic features, consider reading through the Fluent Syntax Guide to understand a more complex example like:
### These messages correspond to security and privacy user interface.
###
### Please choose simple and non-threatening language when localizing
### to help user feel in control when interacting with the UI.
-brand-short-name = Firefox
.gender = masculine
open-settings-button =
{ PLATFORM() ->
[macos] Open System Settings
*[other] Open Settings
}
.title = Open the settings to change how { -brand-short-name } works
## Dialog displayed when disabling container tabs
# Variables:
# $tabCount (Number) - number of container tabs to be closed
containers-disable-alert-ok-button =
{ $tabCount ->
[one] Close { $tabCount } Container Tab
*[other] Close { $tabCount } Container Tabs
}
##
# Variables:
# $version (String) - Version of Firefox, e.g. "60.0"
update-application-info =
You are using { -brand-short-name } Version: { $version }.
Please read the <a data-l10n-name="privacy-url">privacy policy</a>.
The above, of course, is a particular selection of complex strings intended to exemplify the new features and concepts introduced by Fluent. Most localizers don’t edit FTL files directly, but translate Firefox using Pontoon, which supports all these features. On the developer side, linters check FTL files for errors and style issues.
Markup Localization
To localize an element in Fluent, the developer adds a new message to
an FTL file and then has to associate an l10n-id with the element
by defining a data-l10n-id attribute:
<h1 data-l10n-id="home-page-header"></h1>
<button data-l10n-id="open-settings-button"></button>
Fluent will take care of the rest, populating the element with the message value in its content and all localizable attributes if defined.
The developer provides only a single message to localize the whole element, including the value and selected attributes.
The value can be a whole fragment of DOM:
<p data-l10n-id="update-application-info" data-l10n-args='{"version": "60.0"}'>
<a data-l10n-name="privacy-url" href="https://www.mozilla.org/privacy"></a>
</p>
-brand-short-name = Firefox
update-application-info =
You are using { -brand-short-name } Version: { $version }.
Please read the <a data-l10n-name="privacy-url">privacy policy</a>.
Fluent will overlay the translation onto the source fragment preserving attributes like
class and href from the source and adding translations for the elements
inside. The resulting localized content will look like this:
<p data-l10n-id="update-application-info" data-l10n-args='{"version": "60.0"}'>
You are using Firefox Version: 60.0.
Please read the <a data-l10n-name="privacy-url" href="https://www.mozilla.org/privacy">privacy policy</a>.
</p>
The data-l10n-name attribute is what connects the two: each child element
in the source markup that the translation needs to reference must have a
data-l10n-name, and the translation must use an element of the same type
with the same data-l10n-name. In the output, the source element is
replaced by a shallow copy of itself, keeping its attributes, with the text
content and the localizable attributes (like title, or alt for
an image) taken from the translation. This means that attributes like
href or class are not exposed to localizers, and can’t be broken
by a translation. Since the element is copied, event listeners attached to the
source child element are not preserved. The value
of data-l10n-name only needs to be unique within the element, and
should describe the role of the child element.
Text-level elements without functional behavior, like <em>,
<strong>, <b>, <i>, <span> or <br>,
can be used in a translation without a data-l10n-name and without a
counterpart in the source. Any other element used in the translation
without a matching data-l10n-name in the source, like an <a>
or <img>, is not allowed: it’s replaced with its text content, and
a warning is reported in the console.
Note
If you rename a data-l10n-name, or remove the element from the source,
you need to update the message identifier as well, since existing translations
would still reference the old name.
This operation is sanitized, and Fluent takes care of selecting which elements and
attributes can be safely provided by the localization.
The list of allowed elements is based on the text-level semantics defined by the HTML standard, and if
the developer needs to allow for localization of additional attributes, they can
allow them using data-l10n-attrs list:
<label data-l10n-id="search-input" data-l10n-attrs="style"></label>
The above example adds an attribute style to be allowed on this
particular label element.
External Arguments
Notice in the previous example the attribute data-l10n-args, which is
a JSON object storing variables exposed by the developer to the localizer.
This is the main channel for the developer to provide additional variables to be used in the localization.
It’s worth noting that, when the l10n-args are set in
the runtime code, they are in fact encoded as JSON and stored together with
l10n-id as an attribute of the element.
Runtime Localization
In almost every case the JS runtime code will operate on a particular document, either XUL, XHTML or HTML.
If the document links FTL files using <link rel="localization"> (see
Registering New L10n Files), Fluent exposes
a document.l10n property.
This property is an object of type DOMLocalization which maintains the main
localization context for this document and exposes it to runtime code as well.
With a focus on declarative localization, the primary method of localization is to alter the localization attributes in the DOM. Fluent provides a method to facilitate this:
document.l10n.setAttributes(element, "new-panel-header");
This will set the data-l10n-id on the element and translate it before the next
animation frame.
This API can be used to set both the ID and the arguments at the same time.
document.l10n.setAttributes(element, "containers-disable-alert-ok-button", {
tabCount: 5
});
If only the arguments need to be updated, then it’s possible to use the setArgs
method.
document.l10n.setArgs(element, {
tabCount: 5
});
On debug builds if the Fluent arguments are not provided, then Firefox will crash. This is done so that these errors are caught in CI. On rare occasions it may be necessary to work around this crash by providing an empty string as an argument value.
Non-Markup Localization
In rare cases, when the runtime code needs to retrieve the translation and not apply it onto the DOM, Fluent provides an API to retrieve it:
let [ msg ] = await document.l10n.formatValues([
{id: "remove-containers-description"}
]);
alert(msg);
This model is heavily discouraged and should be used only in cases where the DOM annotation is not possible.
Note
This API is asynchronous. In case of Firefox, the only non-DOM localizable calls are used where the output goes to a third-party like Bluetooth, Notifications etc. All those cases should already be asynchronous. If you can’t avoid synchronous access, see Custom Localizations for synchronous contexts.
Internationalization
The majority of internationalization issues are implicitly handled by Fluent without any additional requirement. Full Unicode support and correct number formatting work without any action required from either developer or localizer.
document.l10n.setAttributes(element, "welcome-message", {
userName: "اليسع",
count: 5
});
For example, the same message localized to Arabic will use the Eastern Arabic numeral for number “5”.
Note
Fluent supports wrapping variables in Unicode bidirectional isolation
marks, but these markers are currently disabled in Gecko, as some platforms
don’t support them (see bug 1439018).
This is controlled by the intl.l10n.enable-bidi-marks pref.
Plural Rules
The most common localization feature is the ability to provide different variants of the same string depending on plural categories. Fluent ties into the Unicode CLDR standard called Plural Rules.
In order to allow localizers to use it, all the developer has to do is to pass an external argument number:
document.l10n.setAttributes(element, "unread-warning", { unreadCount: 5 });
Localizers can use the argument to build a multi variant message if their language requires that:
unread-warning =
{ $unreadCount ->
[one] You have { $unreadCount } unread message
*[other] You have { $unreadCount } unread messages
}
If the variant selection is performed based on a number, Fluent matches that number against literal numbers as well as its plural category.
If the given translation doesn’t need pluralization for the string (for example Japanese often will not), the localizer can replace it with:
unread-warning = You have { $unreadCount } unread messages
and the message will preserve the social contract.
One additional feature is that the localizer can further improve the message by specifying variants for particular values:
unread-warning =
{ $unreadCount ->
[0] You have no unread messages
[1] You have one unread message
*[other] You have { $unreadCount } unread messages
}
The advantage here is that per-locale choices don’t leak onto the source code and the developer is not affected.
Note
There is an important distinction between a variant keyed on plural category
one and digit 1. Although in English the two are synonymous, in other
languages category one may be used for other numbers.
For example in Bosnian, category one is used for numbers like 1, 21, 31
and so on, and also for fractional numbers like 0.1.
Partially-Formatted Variables
When it comes to formatting data, Fluent allows the developer to provide a set of parameters for the formatter, and the localizer can fine tune some of them. This technique is called partially-formatted variables.
In Gecko, arguments can only be strings or numbers. To format a date, the
developer passes a timestamp in milliseconds, and uses the DATETIME
function in the message to select the default representation of the date:
document.l10n.setAttributes(element, "session-start-date", {
startDate: new Date(2018, 1, 28).getTime()
});
# Variables:
# $startDate (Date) - Date when the session will start
session-start-date = Your session will start on: { DATETIME($startDate, year: "numeric", month: "long", day: "numeric") }
This would get formatted in the current Firefox as February 28, 2018.
But if in some other locale the string would get too long, the localizer can fine tune the options as well:
session-start-date = Początek Twojej sesji: { DATETIME($startDate, year: "numeric", month: "short", day: "numeric") }
This will adjust the length of the month token in the message to short and get formatted
in Polish as 28 lut 2018.
At the moment Fluent supports two formatters that match JS Intl API counterparts:
NUMBER: Intl.NumberFormat
DATETIME: Intl.DateTimeFormat
Registering New L10n Files
Fluent uses a wildcard statement, packaging all localization resources into
their component’s /localization/ directory.
That means that, if a new file is added to a component of Firefox already
covered by Fluent like browser, it’s enough to add the new file to the
repository in a path like browser/locales/en-US/browser/component/file.ftl, and
the toolchain will package it into browser/localization/browser/component/file.ftl.
At runtime Firefox uses a special registry for all localization data. It will
register the browser’s /localization/ directory and make all files inside it
available to be referenced.
To make the document localized using Fluent, all the developer has to do is add localizable resources for Fluent API to use:
<link rel="localization" href="branding/brand.ftl"/>
<link rel="localization" href="browser/preferences/preferences.ftl"/>
The URIs provided to the <link/> elements are relative paths within the localization
system.
Custom Localizations
The above method creates a single localization context per document. In almost all scenarios that’s sufficient.
In rare edge cases where the developer needs to fetch additional resources, or
the same resources in another language, it is possible to create additional
Localization object manually using the Localization class:
const myL10n = new Localization([
"branding/brand.ftl",
"browser/preferences/preferences.ftl"
]);
let [generalTitle, appearanceTitle] =
await myL10n.formatValues([{id: "pane-general-title"}, {id: "pane-appearance-title"}]);
Example
An example of a use case is the Preferences UI in Firefox, which uses the main context to localize the UI but also to build a search index.
It is common to build such search index both in a current language and additionally in English, since a lot of documentation and online help exist only in English.
A developer may create manually a new context with the same resources as the main one,
but hardcode it to en-US and then build the search index using both contexts.
By default, all Localization contexts are asynchronous. It is possible to create a synchronous
one by passing true as the second argument of the constructor.
const myL10n = new Localization([
"branding/brand.ftl",
"browser/preferences/preferences.ftl"
], true);
let [generalTitle, appearanceTitle] =
myL10n.formatValuesSync([{id: "pane-general-title"}, {id: "pane-appearance-title"}]);
Synchronous contexts should be always avoided as they require synchronous I/O. If you think your use case requires a synchronous localization context, please consult Gecko, Performance and Localization teams.
The same API is available from C++, for code that can’t use JavaScript:
#include "mozilla/intl/Localization.h"
namespace mozilla {
nsresult GetFormStrings(nsACString& aMoreFiles, nsACString& aWarningTitle) {
nsTArray<nsCString> resIds = {"toolkit/global/htmlForm.ftl"_ns};
RefPtr<intl::Localization> l10n = intl::Localization::Create(resIds, true);
ErrorResult rv;
l10n->FormatValueSync("input-file-and-more-files"_ns, {{"fileCount"_ns, 3}},
aMoreFiles, rv);
if (NS_WARN_IF(rv.Failed())) {
return rv.StealNSResult();
}
// Without arguments:
l10n->FormatValueSync("form-post-secure-to-insecure-warning-title"_ns,
aWarningTitle, rv);
return rv.StealNSResult();
}
} // namespace mozilla
Arguments are passed as intl::FluentArg, with strings or numbers as values.
Numbers should be passed as numbers, not formatted strings, so that they can be
used for plural selection and formatted for the locale. Like all Fluent numbers,
they’re stored as double, so integers above 2^53 may lose precision.
When the set of arguments isn’t known in advance, build an array of
intl::FluentArg and pass it instead of a braced list:
void FormatCSPError(intl::Localization* aL10n, const nsACString& aL10nId,
const nsAString& aDirective, const nsACString& aKey,
const nsAString& aValue, nsACString& aResult) {
AutoTArray<intl::FluentArg, 2> l10nArgs = {
intl::FluentArg("directive"_ns, aDirective)};
if (!aKey.IsEmpty()) {
l10nArgs.AppendElement(intl::FluentArg(aKey, aValue));
}
aL10n->FormatValueSync(aL10nId, l10nArgs, aResult, IgnoreErrors());
}
Designing Localizable APIs
When designing localizable APIs, the most important rule is to resolve localization as
late as possible. That means that instead of resolving strings somewhere deep in the
codebase and then passing them on, or even caching, it is highly recommended to pass
around l10n-id or [l10n-id, l10n-args] pairs until the top-most code
resolves them or applies them onto the DOM element.
Testing
When writing tests that involve both I18n and L10n, the general rule is that result strings are opaque. That means that the developer should avoid assuming any particular value, and testing against it, when possible.
In case of raw i18n the resolvedOptions method on all Intl.* formatters
makes it relatively easy. In case of localization, the recommended way is to test that
the code sets the right l10n-id/l10n-args attributes like this:
testedFunction();
const l10nAttrs = document.l10n.getAttributes(element);
deepEquals(l10nAttrs, {
id: "my-expected-id",
args: {
unreadCount: 5
}
});
If the code needs to test for particular values in the localized UI, it is usually better to scan for a variable:
testedFunction();
ok(element.textContent.includes("John"));
Testing against whole values is brittle, since tests will break when the string
changes, but in some cases it’s necessary: for example, when the localized string
itself is the output being tested, like a form validation message exposed through
validationMessage, or a message reported to the console. Tests run with the
en-US locale, so these tests can compare against the English string, and need to
be updated whenever the message changes.
Manually Testing UI with Pseudolocalization
When working with a Fluent-backed UI, the developer gets a new tool to test their UI against several classes of problems.
Pseudolocalization is a mechanism which transforms messages on the fly, using specific logic to help emulate how the UI will look once it gets localized.
The three classes of potential problems that this can help with are:
Hardcoded strings.
Turning on pseudolocalization should expose any strings that were left hardcoded in the source, since they won’t get transformed.
UI space not adapting to longer text.
Many languages use longer strings than English. For example, German strings may be 30% longer (or more). Turning on pseudolocalization is a quick way to test how the layout handles such locales. Strings that don’t fit the space available are truncated and pseudolocalization can also help with detecting them.
Bidi adaptation.
For many developers, testing the UI in right-to-left mode is hard. Pseudolocalization shows how a right-to-left locale will look.
To turn on pseudolocalization, open the Browser Toolbox, click the three dot menu in the top right corner, and choose one of the following:
Enable “accented” locale - [Ȧȧƈƈḗḗƞŧḗḗḓ Ḗḗƞɠŀīīşħ]
This strategy replaces all Latin characters with their accented equivalents, and duplicates some vowels to create roughly 30% longer strings. Strings are wrapped in markers (square brackets), which help with detecting truncation.
This option sets the
intl.l10n.pseudopref toaccented.Enable bidi locale - ɥsıʅƃuƎ ıpıԐ
This strategy replaces all Latin characters with their 180 degree rotated versions and enforces right to left text flow using Unicode UAX#9 Explicit Directional Embeddings. In this mode, the UI directionality will also be set to right-to-left.
This option sets the
intl.l10n.pseudopref tobidi.
Testing Other Locales
Important
For Firefox engineering work, you should prefer using pseudolocales. Especially on Nightly, localizations can be incomplete (as we add/remove localized content all the time) and cause confusing behaviour due to how fallback works.
Instructions on how to install localized builds, use language packs on local builds, or include localization repacks in a Try push are available in the Firefox L10N FAQs. Instructions on how to build localization repacks are available on Localized Builds.
Finding a Regression in a Localized Build
To find a regression in a localized build, you can run mozregression with
localized nightlies. For example, for a Dutch (nl) build:
mozregression --app firefox-l10n --lang nl --good 2024-01-01
Inner Structure of Fluent
The inner structure of Fluent in Gecko is out of scope of this tutorial, but
since the class and file names may show up during debugging or profiling,
below is a list of major components, each with a corresponding file in /intl/l10n
modules in Gecko.
FluentBundle
FluentBundle is the lowest level API. It’s fully synchronous, contains a parser for the FTL file format and a resolver for the logic. It is implemented in Rust, using the fluent-rs crates, and it is not meant to be used by consumers directly.
Localization
Localization is a higher level API which uses FluentBundle internally but
provides a full layer of compound message formatting and robust error fallback.
It is intended for use in runtime code and contains all fundamental localization methods.
DOMLocalization
DOMLocalization extends Localization with functionality to operate on HTML, XUL
and the DOM directly including DOM Overlays and Mutation Observers.
DocumentL10n
DocumentL10n implements the DocumentL10n WebIDL API and allows Document to communicate with DOMLocalization.
Events
DOM translation is asynchronous (e.g., setting a data-l10n-id attribute won’t
immediately reflect the localized content in the DOM).
We expose a Document.hasPendingL10nMutations member that reflects whether
there are any async operations pending. When they are finished, the
L10nMutationsFinished event is fired on the document, so that chrome code can
be certain all the async operations are done.
L10nRegistry
L10nRegistry is our resource management service. It
maintains the state of resources packaged into the build and language packs,
providing an asynchronous iterator of FluentBundle objects for a given locale set
and resources that the Localization class uses.