Skip to main content

Babel Filters

Optional filters provided by the liquid-babel package.

info

Liquid Babel uses Python Babel. Please refer to the Babel docs for more information about working with message catalogs, locales, currency codes and format strings.

Currency

<number> | currency[: group_separator: <boolean>] -> <string>

Currency (aka money) formatting. Return the input number formatted as currency for the current locale.

{{ 100457.99 | currency }}
output
$100,457.99

Use the group_separator argument to control the output of the current locale's group separators.

{{ 100457.99 | currency: group_separator: false }}
output
$100457.99

If the input number is a string, it will be parsed to a decimal according to the current input locale.

{% with input_locale: "de", locale: "en_CA" %}
{{ "100.457,99" | currency }}
{% endwith %}
output
US$100,457.99

Options

Instances of the Currency class default 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 Environment
from liquid_babel.filters import Currency

env = Environment()
env.add_filter("currency", Currency())

template = env.from_string("{{ 100457.99 | currency }}")

print(template.render())
print(template.render(currency_code="GBP"))
print(template.render(locale="de", currency_code="CAD"))
output
$100,457.99
£100,457.99
100.457,99 CA$

This table shows the available Currency() constructor arguments.

ArgumentTypeDescriptionDefault
currency_code_varstrThe name of a render context variable that resolves to the current currency code."currency_code"
default_currency_codestrA fallback currency code if currency_code_var can not be resolved."USD"
locale_varstrThe name of a render context variable that resolves to the current locale."locale"
default_localestrA fallback locale to use if locale_var can not be resolved."en_US"
format_varstrThe name of a render context variable that resolves to the current currency format string."currency_format"
default_formatOptional[str]A fallback currency format that is used if format_var can not be resolved. If None, the standard format for the current locale will be used.None
currency_digitsboolIndicates if the format should override locale specific trailing digit behavior.True
input_locale_varstrThe name of a render context variable that resolves to a locale suitable for parsing input strings to decimals."input_locale"
default_input_localestrA fallback locale to use if input_locale_var can not be resolved."en_US"

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 Environment
from liquid_babel.filters import money
from liquid_babel.filters import money_with_currency
from liquid_babel.filters import money_without_currency
from liquid_babel.filters import money_without_trailing_zeros

env = Environment()
env.add_filter("money", money)
env.add_filter("money_with_currency", money_with_currency)
env.add_filter("money_without_currency", money_without_currency)
env.add_filter("money_without_trailing_zeros", money_without_trailing_zeros)

template = env.from_string("""\
{% 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"))
output
$10.00
$10.00 CAD
10.00
$10

DateTime

<datetime> | datetime[: format: <string>] -> <string>

Date and time formatting. Return the input datetime formatted according to the current locale. If dt is a datetime.datetime object datetime.datetime(2007, 4, 1, 15, 30).

{{ dt | datetime }}
output
Apr 1, 2007, 3:30:00 PM

The optional format argument can be one of 'short', 'medium', 'long', 'full' or a custom format string. format defaults to 'medium'.

{% with timezone: 'America/New_York' %}
{{ dt | datetime: format: 'full' }}
{% endwith %}
output
Sunday, April 1, 2007 at 11:30:00 AM Eastern Daylight Time

If the input datetime is a string, it will be parsed to a datetime object.

{% with locale: 'en_GB' %}
{{ "Apr 1, 2007, 3:30:00 PM UTC+4" | datetime: format: 'short' }}
{% endwith %}
output
01/04/2007, 19:30

Options

Instances of the DateTime class default 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 Environment
from liquid_babel.filters import DateTime

env = Environment()
env.add_filter("datetime", DateTime())

template = env.from_string("{{ '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"))
output
Apr 1, 2007, 3:30:00 PM
1. April 2007 um 15:30:00 UTC
01.04.07, 17:30

This table shows the available DateTime() constructor arguments.

ArgumentTypeDescriptionDefault
timezone_varstrThe name of a render context variable that resolves to a timezone."timezone"
default_timezonestrA fallback timezone to use if timezone_var can not be resolved."UTC"
locale_varstrThe name of a render context variable that resolves to the current locale."locale"
default_localestrA fallback locale to use if locale_var can not be resolved.en_US"
format_varstrThe name of a render context variable that resolves to the current datetime format string."datetime_format"
default_formatstrA fallback datetime format that is used if format_var can not be resolved."medium"
input_timezone_varstrThe name of a render context variable that resolves to a timezone for parsing datetimes entered as strings."input_timezone"
default_input_timezonestrA fallback timezone to use if input_timezone_var can not be resolved."UTC"

Decimal / Number

<number> | decimal[: group_separator: <boolean>] -> <string>

Decimal number formatting. Return the input number formatted as a decimal for the current locale.

{{ '10000.233' | decimal }}
output
10,000.233

Use the group_separator argument to control the output of the current locale's group separators.

{{ '10000.233' | decimal: group_separator: false }}
output
10000.233

If the input number is a string, it will be parsed to a decimal according to the current input locale.

{% with input_locale: "de" %}
{{ "100.457,00" | decimal }}
{% endwith %}
output
100,457

Options

Instances of the Number class default 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 Environment
from liquid_babel.filters import Number

env = Environment()
# Register an instance of the `Number` class as a filter called "decimal".
env.add_filter("decimal", Number())

# Parse a number from a string in the default (en_US) input locale.
template = env.from_string("""\
{{ '10,000.23' | decimal }}
{{ '10,000.23' | decimal: group_separator: false }}
""")

print(template.render(locale="de"))
print(template.render(locale="en_GB"))
output
10.000,23
10000,23

10,000.23
10000.23

This table shows the available Number() constructor arguments.

ArgumentTypeDescriptionDefault
decimal_quantization_varstrThe name of a render context variable that resolves to the decimal quantization to be used."decimal_quantization"
default_decimal_quantizationboolA fallback decimal quantization if decimal_quantization_var can not be resolved.False
locale_varstrThe name of a render context variable that resolves to the current locale."locale"
default_localestrA fallback locale to use if locale_var can not be resolved."en_US"
format_varstrThe name of a render context variable that resolves to the current currency format string."decimal_format"
default_formatOptional[str]A fallback currency format that is used if format_var can not be resolved. If None, the standard format for the current locale will be used.None
input_locale_varstrThe name of a render context variable that resolves to a locale suitable for parsing input strings to decimals."input_locale"
default_input_localestrA fallback locale to use if input_locale_var can not be resolved."en_US"

Translation

New in Liquid Babel version 0.3.0

Instances of the following translation filters default to looking for Translations in a render context variable called translations, falling back to an instance of NullTranslations if translations can not be resolved.

from liquid import Environment
from liquid_babel.filters import GetText

env = Environment()
# Register an instance of the GetText filter as `t`.
env.add_filter("t", GetText())

# You'll need to load an appropriate Translations object.
# `get_translations()` is defined elsewhere.
translations = get_translations(locale="de")

template = env.from_string("{{ 'Hello, World!' | t }}")
print(template.render(translations=translations)) # Hallo Welt!

This table show the options available when instantiating Translate (aka t), GetText, NGetText, PGetText and NPGetText filters.

ArgumentTypeDescriptionDefault
translations_varstrThe name of a render context variable that resolves to a Translations object."translations"
default_translationsOptional[Translations]A fallback Translations object used if translations_var can not be resolved.NullTranslations
message_interpolationboolIf True, do percent-style variable substitution when rendering message text.True
autoescape_messageboolIf True and the current environment has autoescape set to True, translatable messages will be escaped before output.False

To register all included translation filters with an environment, use register_translation_filters(env). It too accepts the arguments described in the table above.

from liquid import Environment
from liquid_babel.filters import register_translation_filters

env = Environment()
# Register `t`, `gettext`, `ngettext`, `pgettext` and `npgettext`
# with HTML auto escaping enabled.
register_translation_filters(env, autoescape_message=True)

t

<string> | t[: <string>[, <identifier>: <object> ... ]] -> <string>

Template internationalization. Return the localized translation of the input message. If a German Translations object is found in the current render context:

{{ "Hello, World!" | t }}
output
Hallo Welt!

If given, the first and only positional argument is a message context string. It will be used to give translators extra information about where the message is to be used. With the default configuration, keyword arguments plural and count are reserved for specifying a pluralizable message.

{{ "Hello, World!" | t: plural: 'Hello, Worlds!', count: 2 }}
output
Hallo Welten!

The remaining keyword arguments are used to populate translatable message variables. If user.name is "Sue":

{{ "Hello, %(you)s" | t: you: user.name }}
output
Hallo Sue!

gettext

<string> | gettext[: <identifier>: <object> ... ]

Return the localized translation of the input message without pluralization or message context.

{{ "Hello, World!" | gettext }}
output
Hallo Welt!

Any keyword arguments are used to populate message variables. If user.name is "Sue":

{{ "Hello, %(you)s" | gettext: you: user.name }}
output
Hallo Sue!

ngettext

<string> | ngettext: <string>, <number> [, <identifier>: <object> ... ]

Return the localized translation of the input message with pluralization. The first positional argument is the plural form of the message. The second is a number used to determine if the singular or plural message should be used.

{% assign count = "Earth,Tatooine" | split: "," | size %}
{{ "Hello, World!" | ngetetxt: "Hello, Worlds!", count }}
output
Hallo Welten!

Any keyword arguments are used to populate message variables. If user.name is "Sue" and count is 1:

{{ "Hello, %(you)s" | ngetetxt: "Hello, everyone!", count, you: user.name }}
output
Hallo Sue!

pgettext

<string> | pgettext: <string> [, <identifier>: <object> ... ]

Return the localized translation of the input message with additional message context. Message context is used to give translators extra information about where the messages is to be used.

{{ "Hello, World!" | pgettext: "extra special greeting" }}
output
Hallo Welt!

Any keyword arguments are used to populate message variables. If user.name is "Sue":

{{ "Hello, %(you)s" | pgettext: "extra special greeting", you: user.name }}
output
Hallo Sue!

npgettext

<string> | npgettext: <string>, <string>, <number> [, <identifier>: <object> ... ]

Return the localized translation of the input message with pluralization and a message context. The first positional argument is the message context string, the second is the plural form of the message, and the third is a number used to determine if the singular or plural message should be used.

{% assign count = "Earth,Tatooine" | split: "," | size %}
{{ "Hello, World!" | ngetetxt: "extra special greeting", "Hello, Worlds!", count }}
output
Hallo Welten!

Any keyword arguments are used to populate message variables. If user.name is "Sue" and count is 1:

{{ "Hello, %(you)s" | ngetetxt: "extra special greeting", "Hello, everyone!", count, you: user.name }}
output
Hallo Sue!

Unit

New in Liquid Babel version 1.0.0

<number> | unit: <string>
[, denominator: <number>]
[, denominator_unit: <string>]
[, length: <string>]
[, format: <string>]

Measurement units formatting. Return the input number formatted with the given units according to the current locale. The first, required positional argument is a CLDR measurement unit code.

{{ 12 | unit: 'length-meter' }}
output
12 meters

length

length can be one of "short", "long" or "narrow", defaulting to "long".

{{ 12 | unit: 'length-meter' }}
{{ 12 | unit: 'length-meter', length: 'short' }}
{{ 12 | unit: 'length-meter', length: 'long' }}
{{ 12 | unit: 'length-meter', length: 'narrow' }}
output
12 meters
12 m
12 meters
12m

Or, if the current locale is set to fr.

{% with locale:"fr" %}
{{ 12 | unit: 'length-meter' }}
{{ 12 | unit: 'length-meter', length: 'short' }}
{{ 12 | unit: 'length-meter', length: 'long' }}
{{ 12 | unit: 'length-meter', length: 'narrow' }}
{% endwith %}
output
12 mètres
12 m
12 mètres
12m

format

format is an optional decimal format string, described in the Locale Data Markup Language specification (LDML).

{{ 12 | unit: 'length-meter', format: '#,##0.00' }}
output
12.00 meters

Compound Units

If a denominator and/or denominator_unit is given, the value will be formatted as a compound unit.

{{ 150 | unit: 'kilowatt', denominator_unit: 'hour' }}
{{ 32.5 | unit: 'ton', denominator: 15, denominator_unit: 'hour' }}
output
150 kilowatts per hour
32.5 tons per 15 hours

Or, if the current locale is set to fi.

{% with locale:"fi" %}
{{ 150 | unit: 'kilowatt', denominator_unit: 'hour' }}
{{ 32.5 | unit: 'ton', denominator: 15, denominator_unit: 'hour' }}
{% endwith %}
output
150 kilowattia / tunti
32,5 am. tonnia/15 tuntia

Options

Instances of the Unit class default 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 Environment
from liquid_babel.filters import Unit

env = Environment()
env.add_filter("unit", Unit())

template = env.from_string("""\
{{ 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"))
output
12.00 meters
150 kilowatts per hour

12,00 Meter
150 Kilowatt pro Stunde

This table show the available Unit() constructor arguments.

ArgumentTypeDescriptionDefault
length_varstrThe name of a render context variable that resolves to a unit format length."unit_length"
default_lengthstrA fallback format length to use if length_var can not be resolved. Should be one of "short", "long" or "narrow"."long"
locale_varstrThe name of a render context variable that resolves to the current locale."locale"
default_localestrA fallback locale to use if locale_var can not be resolved."en_US"
format_varstrThe name of a render context variable that resolves to the current unit decimal format string."unit_format"
default_formatOptional[str]A fallback decimal format that is used if format_var can not be resolved. If None, the standard format for the current locale will be used.None
input_locale_varstrThe name of a render context variable that resolves to a locale suitable for parsing input strings to decimals."input_locale"
default_input_localestrA fallback locale to use if input_locale_var can not be resolved."en_US"