Translating Strings in Jinja Expressions
n
i18n extension provides a set of dedicated functions that allow you to translate strings directly within your template expressions. This gives you the flexibility to translate content that isn’t in a standalone block, such as titles, link text, or dynamic messages, making your templates even more adaptable for a global audience.nnnn
nn
Available Translation Functions
nWhen the i18n extension is enabled, Jinja makes several powerful translation functions available for use in your expressions. These functions are the core of the gettext system, which is a standard for internationalization. They include:n
- n
_()(alias forgettext()): The most common function. It takes a single string message and returns its translated version. This is ideal for simple phrases or words.ngettext(singular, plural, n): Used for handling pluralization. This function takes a singular string, a plural string, and a count (`n`). It returns the correct form based on the count.pgettext(context, message): For handling words with multiple meanings (e.g., “apple” as a fruit vs. the company). It takes a context string and a message, returning the correct translation based on that context.npgettext(context, singular, plural, n): The pluralization version ofpgettext, combining both a context and a count to select the correct translation.
n
n
n
n
nYou can use these functions directly within a standard variable expression to display a translated string. For instance, to translate a simple “Hello, World!” message, you would write:n
n{{ _("Hello, World!") }}nn
nn
nn
Using Placeholders with the Format Filter
nOften, your translatable string will need to include dynamic data, such as a user’s name. When translating strings in expressions, you should **use placeholders with the format filter** instead of directly embedding variables. This is a crucial step for proper internationalization, as it ensures that the order of words can be changed in the translated language. The best practice is to always use **keyword arguments** with the `format` filter. For example:n
n{{ _("Hello, %(user)s!")|format(user=user.username) }}nnIn this code, the placeholder `%(user)s` is a clear marker for the translator, who can move it to the correct position in the sentence for their language. Using keyword arguments like `user=user.username` ensures that the placeholders always match the correct value, even if the order of words is different. This is far safer and more flexible than using positional arguments (e.g., `format(user.username)`), which can easily break translations that require a different word order.nn
nn
nn
n
