Babel¶
This page covers i18n and l10n filter and tag configuration, and how we support translations and translation message catalogs. See Extra filters for usage examples.
Currency¶
The currency filter returns the input number formatted as currency for the current locale.
- class liquid.filters.Currency(*, currency_code_var: str = 'currency_code', default_currency_code: str = 'USD', locale_var: str = 'locale', default_locale: str = 'en_US', format_var: str = 'currency_format', default_format: str | None = None, currency_digits: bool = True, input_locale_var: str = 'input_locale', default_input_locale: str = 'en_US')
A Liquid filter for formatting currency values.
- Parameters:
currency_code_var – The name of a render context variable that resolves to the current currency code. Defaults to
"currency_code".default_currency_code – A fallback currency code if currency_code_var can not be resolved. Defaults to
"USD".locale_var – The name of a render context variable that resolves to the current locale. Defaults to
"locale".default_locale – A fallback locale to use if locale_var can not be resolved. Defaults to
"en_US".format_var – The name of a render context variable that resolves to the current currency format string. Defaults to
"currency_format".default_format – A fallback currency format that is used if format_var can not be resolved. Defaults to None, which means the standard format for the current locale will be used.
currency_digits – Indicates if the format should override locale specific trailing digit behavior. Defaults to
False.input_locale_var – The name of a render context variable that resolves to a locale suitable for parsing input strings to decimals. Defaults to
"input_locale".default_input_locale – A fallback locale to use if input_locale_var can not be resolved. Defaults to
"en_US".
currency defaults to looking for a locale in a render context variable called
locale, and a currency code in a render context variable called currency_code. It
outputs in the locale’s standard format and falls back to en_US and USD if those
context variables don’t exist.
from liquid import parse
template = parse("{{ 100457.99 | currency }}")
print(template.render())
print(template.render(currency_code="GBP"))
print(template.render(locale="de", currency_code="CAD"))
$100,457.99
£100,457.99
100.457,99 CA$
To configure currency, register a new instance of liquid.filters.Currency with an
liquid.Environment, then render your templates from that.
from liquid.filters import Currency
from liquid import Environment
env = Environment()
env.filters["currency"] = Currency(default_locale="de")
Money¶
For convenience, some money filters are defined that mimic Shopify’s money filter behavior. These are instances of Currency with specific default formats. All other currency options are set to their defaults.
from liquid import parse
template = parse("""\
{% assign amount = 10 %}
{{ amount | money }}
{{ amount | money_with_currency }}
{{ amount | money_without_currency }}
{{ amount | money_without_trailing_zeros }}""")
print(template.render(currency_code="CAD", locale="en_CA"))
$10.00
$10.00 CAD
10.00
$10
DateTime¶
The datetime filter returns the input datetime.datetime formatted
for the current locale.
- class liquid.filters.DateTime(*, timezone_var: str = 'timezone', default_timezone: str = 'UTC', locale_var: str = 'locale', default_locale: str = 'en_US', format_var: str = 'datetime_format', default_format: str = 'medium', input_timezone_var: str = 'input_timezone', default_input_timezone: str = 'UTC')
A Liquid filter for formatting datetime objects.
- Parameters:
timezone_var – The name of a render context variable that resolves to a timezone. Defaults to
"timezone".default_timezone – A fallback timezone to use if timezone_var can not be resolved. Defaults to
"UTC".locale_var – The name of a render context variable that resolves to the current locale. Defaults to
"locale".default_locale – A fallback locale to use if locale_var can not be resolved. Defaults to
"en_US".format_var – The name of a render context variable that resolves to the current datetime format string. Defaults to
"datetime_format".default_format – A fallback datetime format that is used if format_var can not be resolved. Defaults to
"medium".input_timezone_var – The name of a render context variable that resolves to a timezone for parsing datetimes entered as strings. Defaults to
"input_timezone".default_input_timezone – A fallback timezone to use if input_timezone_var can not be resolved. Defaults to
"UTC".
datetime defaults to looking for a timezone in a render context variable called
timezone, a locale in a render context variable called locale and a datetime
format in a render context variable called datetime_format.
from liquid import parse
template = parse("{{ 'Apr 1, 2007, 3:30:00 PM' | datetime }}")
print(template.render())
print(template.render(locale="de", datetime_format="long"))
print(template.render(locale="de", timezone="CET", datetime_format="short"))
Apr 1, 2007, 3:30:00 PM
1. April 2007 um 15:30:00 UTC
01.04.07, 17:30
To configure datetime, register a new instance of liquid.filters.DateTime with an
instance of liquid.Environment, then render your templates from that.
from liquid.filters import DateTime
from liquid import Environment
env = Environment()
env.filters["datetime"] = DateTime(timezone_var="tz")
Decimal¶
The decimal filter returns the input number formatted as a decimal for the current locale.
- class liquid.filters.Number(*, decimal_quantization_var: str = 'decimal_quantization', default_decimal_quantization: bool = False, locale_var: str = 'locale', default_locale: str = 'en_US', format_var: str = 'decimal_format', default_format: str | None = None, input_locale_var: str = 'input_locale', default_input_locale: str = 'en_US')
A Liquid filter for formatting decimal values.
- Parameters:
decimal_quantization_var – The name of a render context variable that resolves to the decimal quantization to be used. Defaults to
"decimal_quantization".default_decimal_quantization – A fallback decimal quantization if decimal_quantization_var can not be resolved. Defaults to
False.locale_var – The name of a render context variable that resolves to the current locale. Defaults to
"locale".default_locale – A fallback locale to use if locale_var can not be resolved. Defaults to
"en_US".format_var – The name of a render context variable that resolves to the current decimal format string. Defaults to
"decimal_format".default_format – A fallback decimal format that is used if format_var can not be resolved. Defaults to
None, which means the standard format for the current locale will be used.input_locale_var – The name of a render context variable that resolves to a locale suitable for parsing input strings to decimals. Defaults to
"input_locale".default_input_locale – A fallback locale to use if input_locale_var can not be resolved. Defaults to
"en_US".
decimal defaults to looking for a locale in a render context variable called
locale. It uses the locale’s standard format and falls back to en_US if that
variable does not exist.
from liquid import parse
# Parse a number from a string in the default (en_US) input locale.
template = parse("""\
{{ '10,000.23' | decimal }}
{{ '10,000.23' | decimal: group_separator: false }}
""")
print(template.render(locale="de"))
print(template.render(locale="en_GB"))
10.000,23
10000,23
10,000.23
10000.23
To configure decimal, register a new instance of liquid.filters.Number with an
instance of liquid.Environment, then render your templates from that.
from liquid.filters import Number
from liquid import Environment
env = Environment()
env.filters["decimal"] = Number(default_locale="en_GB")
Unit¶
The unit filter returns he input number formatted with the given units according to the current locale.
- class liquid.filters.Unit(*, locale_var: str = 'locale', default_locale: str = 'en_US', length_var: str = 'unit_length', default_length: str = 'long', format_var: str = 'unit_format', default_format: str | None = None, input_locale_var: str = 'input_locale', default_input_locale: str = 'en_US')
A Liquid filter for formatting units of measurement.
- Parameters:
locale_var – The name of a render context variable that resolves to the current locale. Defaults to
"locale".default_locale – A fallback locale to use if locale_var can not be resolved. Defaults to
"en_US".length_var – The name of a render context variable that resolves to a unit format length. Should be one of
"short","long"or"narrow". Defaults to"long".default_length – A fallback format length to use if length_var can not be resolved.
format_var – The name of a render context variable that resolves to a decimal format string. Defaults to
"unit_format".default_format – A fallback decimal format to use if format_var can not be resolved. Defaults to
None, meaning the locale’s standard decimal format is used.input_locale_var – The name of a render context variable that resolves to a locale suitable for parsing input strings to decimals. Defaults to
"input_locale".default_input_locale – A fallback locale to use if input_locale_var can not be resolved. Defaults to
"en_US".
unit defaults to looking for a locale in a render context variable called locale,
a length in a render context variable called unit_length, and a decimal format in a
render context variable called unit_format.
from liquid import parse
template = parse("""\
{{ 12 | unit: 'length-meter', format: '#,##0.00' }}
{{ 150 | unit: 'kilowatt', denominator_unit: 'hour' }}
""")
print(template.render(unit_length="long"))
print(template.render(locale="de", unit_length="long"))
12.00 meters
150 kilowatts per hour
12,00 Meter
150 Kilowatt pro Stunde
To configure unit, register a new instance of liquid.filters.Unit with an
instance of liquid.Environment, then render your templates from that.
from liquid.filters import Unit
from liquid import Environment
env = Environment()
env.filters["unit"] = Unit(locale_var="_locale")
Translations¶
Python Liquid includes gettext, ngettext, pgettext and npgettext filters equivalent to the functions found in Python’s gettext module.
Additionally there’s the t filter which can behave like any of the
*gettext filters depending on its arguments. Where the *gettext filters require
positional arguments for context, count and plural, t reserves optional
count and plural keyword arguments.
Liquid Babel also offers a translate tag. This is similar to the
{% trans %} tag found in Jinja or the {% blocktranslate %} tag found in
Django’s template language.
Filters¶
gettext, ngettext, pgettext and
npgettext filters all default to looking for Message catalogs in a
render context variable called translations, falling back to an instance of
NullTranslations if translations can not be resolved.
from liquid import parse
# You'll need to load an appropriate Translations object.
# `get_translations()` is defined elsewhere.
translations = get_translations(locale="de")
template = parse("{{ 'Hello, World!' | t }}")
print(template.render(translations=translations)) # Hallo Welt!
Message catalogs¶
By default, all translation filters and tags will look for a render context variable
called translations, which must be an object implementing the Translations
protocol. It is the application developer’s responsibility to provide a Translations
object, being the interface between Liquid and a message catalog.
The Translations protocol is defined as follows. It is simply a subset of the
NullTranslations class found in the gettext module.
class Translations(Protocol):
def gettext(self, message: str) -> str: ...
def ngettext(self, singular: str, plural: str, n: int) -> str: ...
def pgettext(self, context: str, message: str) -> str: ...
def npgettext(self, context: str, singular: str, plural: str, n: int) -> str: ...
It could be a GNUTranslations instance, a Babel Translations instance, or any
object implementing gettext, ngettext, pgettext and npgettext methods.
Message variables¶
Translatable message text can contain placeholders for variables. When using variables in
strings to be translated by filters, variables are defined using percent-style formatting.
Only the s modifier is supported and every variable must have a name. In this example
you is the variable name.
{{ "Hello, %(you)s!" | t }}
Filter keyword arguments are merged with the current render context before being used to replace variables in message text. All variables are converted to their string representation before substitution. Dotted property/attribute access is not supported inside message variables.
{{ "Hello, %(you)s!" | t: you: user.name }}
The translate block tag recognizes simplified Liquid output statements as translation message variables. These variables must be valid identifiers without dotted or bracketed property/attribute access, and no filters.
{% translate %}
Hello, {{ you }}!
{% endtranslate %}
Keyword arguments passed to the translate tag will be merged with the current render context before being used to replace variables in message text.
{% translate you: user.name, count: users.size %}
Hello, {{ you }}!
{% plural %}
Hello, {{ you }}s!
{% endtranslate %}
Message Extraction¶
Use the liquid.extract_from_template() function to build a message catalog from
one or more templates. You are then free to make use of Babel’s PO file features, or
convert the catalog to a more convenient internal representation.
import io
from babel.messages.pofile import write_po
from liquid import extract_from_templates, parse
source = """
{% # Translators: some comment %}
{{ 'Hello, World!' | t }}
{% comment %}Translators: other comment{% endcomment %}
{% translate count: 2 %}
Hello, {{ you }}!
{% plural %}
Hello, all!
{% endtranslate %}
"""
template = parse(source, name="something.liquid")
catalog = extract_from_templates(template)
buf = io.BytesIO()
write_po(buf, catalog, omit_header=True)
print(buf.getvalue().decode("utf-8"))
#. Translators: some comment
#: something.liquid:3
msgid "Hello, World!"
msgstr ""
#. Translators: other comment
#: something.liquid:5
#, python-format
msgid "Hello, %(you)s!"
msgid_plural "Hello, all!"
msgstr[0] ""
msgstr[1] ""
Translator Comments¶
When a Liquid comment tag immediately precedes a translatable filter or tag, and the
comment starts with a string in comment_tags, that comment will be included as a
translator comment with the message. Use the comment_tags argument to
liquid.extract_liquid(), or liquid.extract_from_templates() to change
translator comment prefixes. The default is ["Translators:"].
from liquid import extract_from_templates, parse
source = """
{% # Translators: some comment %}
{{ 'Hello, World!' | t }}
{% comment %}Translators: other comment{% endcomment %}
{% translate count: 2 %}
Hello, {{ you }}!
{% plural %}
Hello, all!
{% endtranslate %}
"""
template = parse(source, name="something.liquid")
catalog = extract_from_templates(template, strip_comment_tags=True)
message = catalog.get("Hello, World!")
print(message.auto_comments[0]) # some comment