API: View Helpers

format_date

Formats a date/datetime according to the current locale and timezone.

format_date(
    date: datetime.date | None = None,
    format: str = 'medium',
    *,
    timezone: str | datetime.tzinfo | None = None,
    locale: str = 'en'
) -> str
Argument Description
date The date or datetime object; if None, the current datetime
is used.
format "full", "long", "medium", "short", or a custom date/time pattern.
timezone Force the timezone to use for formatting.
locale Force the locale to use for formatting.
format_date(date(2007, 4, 1), locale='en_US')
# => 'Apr 1, 2007'

format_date(datetime(2007, 4, 1, 15, 30), locale='en_US')
# => 'Apr 1, 2007, 3:30:00 PM'

You can also specify a custom date pattern:

format_date(date(2007, 4, 1), "EEE, MMM d, ''yy", locale='en')
# => "Sun, Apr 1, '07"

format_date(
    datetime(2007, 4, 1, 15, 30),
    "yyyy.MM.dd G 'at' HH:mm:ss zzz",
    timezone='US/Eastern',
    locale='en'
)
# => '2007.04.01 AD at 11:30:00 EDT'

format_interval

Formats an interval between two dates or times according to the timezone and locale's rules.

format_interval(
    start: datetime.date | datetime.time | float,
    end: datetime.date | datetime.time | float,
    skeleton: str | None = None,
    *,
    fuzzy: bool = True,
    timezone: str | datetime.tzinfo | None = None,
    locale: str = 'en'
) -> str
Argument Description
start First instant (datetime/date/time)
end Second instant (datetime/date/time)
skeleton The "skeleton format" to use for formatting.
fuzzy If the skeleton is not found, allow choosing a skeleton that's close
enough to it.
timezone Force the timezone to use for formatting, if none is already attached.
locale Force the locale to use for formatting.
format_interval(time(5, 12), time(16, 24), "Hm", locale="en_GB")
# => '5:12–16:24'

format_interval(time(5, 12), time(16, 24), "hm", locale="en_US")
# => '5:12 AM – 4:24 PM'

format_interval(date(2016, 1, 15), date(2016, 1, 17), "yMd", locale="fi")
# => '15.–17.1.2016'

If the start instant equals the end instant, the interval is formatted like the instant.

format_interval(time(16, 18), time(16, 18), "Hm", locale="it")
# => '16:18'

Unknown skeletons fall back to "default" formatting.

format_interval(date(2015, 1, 1), date(2017, 1, 1), "wzq", locale="ja")
# => '2015/01/01~2017/01/01'

format_interval(date(2016, 1, 15), date(2016, 1, 17), "xxx", locale="de")
# => '15.01.2016 – 17.01.2016'

format_skeleton

Formats a datetime according to the given pattern, timezone and locale rules.

format_skeleton(
    datetime: datetime.datetime | None = None,
    skeleton: str = 'yMMMd',
    *,
    fuzzy: bool = True,
    timezone: str | datetime.tzinfo | None = None,
    locale: str = 'en'
) -> str
Argument Description
datetime The datetime object; if None, the current datetime in UTC is used.
skeleton A date time skeleton as defined in the cldr data.
fuzzy If the skeleton is not found, allow choosing a skeleton that's close
enough to it. If there is no close match, a KeyError is thrown.
timezone Force the timezone to use for formatting.
locale Force the locale to use for formatting.

The skeletons are defined in the CLDR data and provide more flexibility than the simple short/long/medium formats, but are a bit harder to use. The are defined using the date/time symbols without order or punctuation and map to a suitable format for the given locale.

t = datetime(2007, 4, 1, 15, 30)

format_skeleton(t, 'MMMEd', locale='fr')
# => 'dim. 1 avr.'

format_skeleton(t, 'MMMEd', locale='en')
# => 'Sun, Apr 1'

# yMMd is not in the Finnish locale; yMd gets used
format_skeleton(t, 'yMMd', locale='fi')
# => '1.4.2007'

# yMMd is not in the Finnish locale, an error is thrown
format_skeleton(t, 'yMMd', fuzzy=False, locale='fi')
Traceback (most recent call last):
    ...
KeyError: yMMd

# GH is not in the Finnish locale and there is no close match,
# an error is thrown
format_skeleton(t, 'GH', fuzzy=True, locale='fi_FI')
Traceback (most recent call last):
    ...
KeyError: None

format_time

Formats a time according to the current locale and timezone.

format_time(
    time: datetime.time | datetime.datetime | float | None = None,
    format: str = 'medium',
    *,
    timezone: str | datetime.tzinfo | None = None,
    locale: str = 'en'
) -> str
Argument Description
time The time or datetime object; if None, the current
time in UTC is used.
format Either "full", "long", "medium", or "short", or a custom
date/time pattern.
timezone Force the timezone to use for formatting.
locale Force the locale to use for formatting.
t =

format_time(time(15, 30), locale='en_US')
# => '3:30:00 PM'

format_time(time(15, 30), format='short', locale='de_DE')
# => '15:30'

You can also specify a custom time pattern:

format_time(time(15, 30), "hh 'o''clock' a", locale='en')
# => "03 o'clock PM"

For any pattern requiring the display of the time-zone a timezone has to be specified explicitly:

dt = datetime(2007, 4, 1, 15, 30).astimezone(get_timezone('Europe/Paris'))

format_time(dt, format='full', timezone='Europe/Paris', locale='fr_FR')
# => '15:30:00 heure d’été d’Europe centrale'

format_time(
    dt, "hh 'o''clock' a, zzzz",
    timezone='US/Eastern',
    locale='en'
)
# => "09 o'clock AM, Eastern Daylight Time"

As that example shows, when this function gets passed a datetime.datetime value, the actual time in the formatted string is adjusted to the timezone specified by the timezone parameter. If the datetime is "naive" (i.e. it has no associated timezone information), it is assumed to be in UTC.

These timezone calculations are not performed if the value is of type datetime.time, as without date information there's no way to determine what a given time would translate to in a different timezone without information about whether daylight savings time is in effect or not. This means that time values are left as-is, and the value of the timezone parameter is only used to display the timezone name if needed:

format_time(
    time(15, 30),
    format='full',
    timezone='Europe/Paris',
    locale='fr_FR'
)
# => '15:30:00 heure normale d’Europe centrale'

format_time(
    time(15, 30),
    format='full',
    timezone='US/Eastern',
    locale='en_US'
)
# => '3:30:00 PM Eastern Standard Time'

format_timedelta

Formats a timedelta according to the rules of the given locale.

format_timedelta(
    delta: datetime.timedelta | int,
    *,
    granularity: Literal['year', 'month', 'week', 'day', 'hour', 'minute', 'second'] = 'second',
    threshold: float = 0.85,
    add_direction: bool = False,
    format: Literal['narrow', 'short', 'long'] = 'long',
    locale: str = 'en'
) -> str
Argument Description
delta A timedelta object representing the time difference to
format, or the delta in seconds as an int value
granularity Determines the smallest unit that should be displayed,
the value can be either "year", "month", "week", "day",
"hour", "minute" or "second"
threshold Factor that determines at which point the presentation
switches to the next higher unit
add_direction If this flag is set to True, a positive timedelta will mean
the future (eg. in 1 hour) and a negative timedelta the past
(eg. 1 hour ago).
format Can be "narrow", "short" or "long".
locale Force the locale to use for formatting.
format_timedelta(timedelta(weeks=12), locale='en_US')
# => '3 months'

format_timedelta(timedelta(seconds=1), locale='es')
# => '1 segundo'

The granularity parameter can be provided to alter the lowest unit presented, which defaults to a second.

format_timedelta(timedelta(hours=3), granularity='day', locale='en_US')
# => '1 day'

The threshold parameter can be used to determine at which value the presentation switches to the next higher unit. A higher threshold factor means the presentation will switch later. For example:

format_timedelta(timedelta(hours=23), threshold=0.9, locale='en_US')
# => '1 day'

format_timedelta(timedelta(hours=23), threshold=1.1, locale='en_US')
# => '23 hours'

In addition directional information can be provided that informs the user if the date is in the past or in the future:

format_timedelta(timedelta(hours=1), add_direction=True, locale='en')
# => 'in 1 hour'

format_timedelta(timedelta(hours=-1), add_direction=True, locale='en')
# => '1 hour ago'

The format parameter controls how compact or wide the presentation is:

format_timedelta(timedelta(hours=3), format='short', locale='en')
# => '3 hr'

format_timedelta(timedelta(hours=3), format='narrow', locale='en')
# => '3h'

format_compact_currency

Like format_currency but in compact form.

format_compact_currency(
    number: float | decimal.Decimal | str,
    currency: str,
    *,
    fraction_digits: int = 0,
    numbering_system: str = 'latn',
    locale: str = 'en'
) -> str
Argument Description
number the number to format.
currency the currency code.
fraction_digits number of digits after the decimal point to use. Defaults to 0.
numbering_system the numbering system used for formatting number symbols. Defaults to "latn".
the special value "default" will use the default numbering system of the locale.
locale force the locale to use for formatting.
format_compact_currency(12_345, 'USD', locale='en_US')
# => '$12K'
format_compact_currency(123_456_789, 'USD', locale='en_US', fraction_digits=2)
# => '$123.46M'
format_compact_currency(123_456_789, 'EUR', locale='de_DE', fraction_digits=1)
# => '123,5 Mio. €'

Raises:

  • If the numbering system is not supported by the locale.

format_compact_decimal

Like format_decimal but in compact form.

format_compact_decimal(
    number: float | decimal.Decimal | str,
    *,
    format_type: Literal['short', 'long'] = 'short',
    fraction_digits: int = 0,
    numbering_system: str = 'latn',
    locale: str = 'en'
) -> str
Argument Description
number the number to format.
format_type compact format to use ("short" or "long").
fraction_digits number of digits after the decimal point to use. Defaults to 0.
numbering_system the numbering system used for formatting number symbols. Defaults to "latn".
the special value "default" will use the default numbering system of the locale.
locale force the locale to use for formatting.
format_compact_decimal(12_345, format_type="short", locale='en_US')
# => '12K'

format_compact_decimal(12_345, format_type="long", locale='en_US')
# => '12 thousand'

format_compact_decimal(12_345, format_type="short", locale='en_US', fraction_digits=2)
# => '12.34K'

format_compact_decimal(1_234_567, format_type="short", locale="ja_JP")
# => '123万'

format_compact_decimal(2_345_678, format_type="long", locale="mk")
# => '2 милиони'

format_compact_decimal(21_000_000, format_type="long", locale="mk")
# => '21 милион'

format_compact_decimal(12_345, format_type="short", locale='ar_EG', fraction_digits=2, numbering_system='default')
# => '12٫34 ألف'

Raises:

  • If the numbering system is not supported by the locale.

format_currency

Formats a number (as a float, Decimal, or string) as a currency value, following the locale's formatting rules.

format_currency(
    number: float | decimal.Decimal | str,
    currency: str,
    *,
    format: str | None = None,
    currency_digits: bool = True,
    format_type: Literal['name', 'standard', 'accounting'] = 'standard',
    quantization: bool = True,
    group_separator: bool = True,
    numbering_system: str = 'latn',
    locale: str = 'en'
) -> str
Argument Description
number The number to format.
currency The currency code.
format The format string to use.
format_type The currency format type to use. Can be "name", "standard" or "accounting".
Defaults to "standard".
currency_digits Use the currency's natural number of decimal digits or not. Defaults to True.
quantization Truncate and round high-precision numbers to the format pattern. Defaults to True.
group_separator Boolean to switch group separator on/off in a locale's number format.
numbering_system The numbering system used for formatting number symbols. Defaults to "latn".
The special value "default" will use the default numbering system of the locale.
locale Force the locale to use for formatting.
format_currency(1_099.98, 'USD', locale='en_US')
# => '$1,099.98'

format_currency(1_099.98, 'USD', locale='es_CO')
# => 'US$1.099,98'

format_currency(1_099.98, 'EUR', locale='de_DE')
# => '1.099,98 €'

format_currency(1_099.98, 'EGP', locale='ar_EG', numbering_system='default')
# => '‏1٬099٫98 ج.م.‏'

The format can also be specified explicitly. The currency is placed with the '¤' sign. As the sign gets repeated the format expands (¤ being the symbol, ¤¤ is the currency abbreviation and ¤¤¤ is the full name of the currency):

format_currency(1_099.98, 'EUR', format='¤¤ #,##0.00', locale='en_US')
# => 'EUR 1,099.98'
format_currency(1_099.98, 'EUR', format='#,##0.00 ¤¤¤', locale='en_US')
# => '1,099.98 euros'

Currencies usually have a specific number of decimal digits. This function favours that information over the given format:

format_currency(1_099.98, 'JPY', locale='en_US')
# => '¥1,100'

format_currency(1_099.98, 'COP', format='#,##0.00', locale='es_ES')
# => '1.099,98'

However, the number of decimal digits can be overridden from the currency information, by setting the last parameter to False:

format_currency(1_099.98, 'JPY', locale='en_US', currency_digits=False)
# => '¥1,099.98'

format_currency(1_099.98, 'COP', format='#,##0.00', locale='es_ES', currency_digits=False)
# => '1.099,98'

If a format is not specified the type of currency format to use from the locale can be specified:

format_currency(1_099.98, 'EUR', locale='en_US', format_type='standard')
# => '€1,099.98'

When the given currency format type is not available, an exception is raised:

format_currency('1_099.98', 'EUR', locale='root', format_type='unknown')
Traceback (most recent call last):
    ...
UnknownCurrencyFormatError: "'unknown' is not a known currency format type"

You can also switch the group separator off:

format_currency(101_299.98, 'USD', locale='en_US', group_separator=False)
# => '$101299.98'

You can also pass format_type='name' to use long display names. The order of the number and currency name, along with the correct localized plural form of the currency name, is chosen according to locale:

format_currency(1, 'USD', locale='en_US', format_type='name')
# => '1.00 US dollar'

format_currency(1_099.98, 'USD', locale='en_US', format_type='name')
# => '1,099.98 US dollars'

format_currency(1_099.98, 'USD', locale='ee', format_type='name')
# => 'us ga dollar 1,099.98'

By default the locale is allowed to truncate and round a high-precision number by forcing its format pattern onto the decimal part. You can bypass this behavior with the quantization parameter:

format_currency(1_099.9876, 'USD', locale='en_US')
# => '$1,099.99'

format_currency(1_099.9876, 'USD', locale='en_US', quantization=False)
# => '$1,099.9876'

Raises:

  • If the numbering system is not supported by the locale.

format_decimal

Formats a number for a specific locale.

format_decimal(
    number: float | decimal.Decimal | str,
    *,
    quantization: bool = True,
    group_separator: bool = True,
    numbering_system: str = 'latn',
    locale: str = 'en'
) -> str
Argument Description
number the number to format.
quantization truncate and round high-precision numbers to the format pattern. Defaults to True.
group_separator boolean to switch group separator on/off in a locale's number format.
numbering_system the numbering system used for formatting number symbols. Defaults to "latn".
the special value "default" will use the default numbering system of the locale.
locale force the locale to use for formatting.
format_decimal(12345.5, locale='en_US')
# => '12,345.5'

format_decimal(1.2345, locale='de')
# => '1,234'

You can also switch the group separator off:

format_decimal(12345.67, locale='fr_CA', group_separator=False)
# => '12345,67'

By default the locale is allowed to truncate and round a high-precision number by forcing its format pattern onto the decimal part. You can bypass this behavior with the quantization parameter:

format_decimal(1.2346, locale='en_US')
# => '1.235'

format_decimal(1.2346, locale='en_US', quantization=False)
# => '1.2346'

Raises:

  • If the numbering system is not supported by the locale.

format_percent

Return formatted percent value following the locale's formatting rules.

format_percent(
    number: float | decimal.Decimal | str,
    *,
    format: str | None = None,
    quantization: bool = True,
    group_separator: bool = True,
    numbering_system: str = 'latn',
    locale: str = 'en'
) -> str
Argument Description
number The number to format as a percent.
format The format string to use.
quantization Truncate and round high-precision numbers to the format pattern. Defaults to True.
group_separator Boolean to switch group separator on/off in a locale's number format.
numbering_system The numbering system used for formatting number symbols. Defaults to "latn".
The special value "default" will use the default numbering system of the locale.
locale Force the locale to use for formatting.
format_percent(0.34, locale='en_US')
# => '34%'

format_percent(25.1234, locale='en_US')
# => '2,512%'

format_percent(25.1234, locale='sv_SE')
# => '2 512 %'

format_percent(25.1234, locale='ar_EG', numbering_system='default')
# => '2٬512%'

The format pattern can also be specified explicitly:

format_percent(25.1234, format='#,##0‰', locale='en_US')
# => '25,123‰'

And you can switch the group separator off:

format_percent(229_291.1234, locale='pt_BR', group_separator=False)
# => '22929112%'

By default the locale is allowed to truncate and round a high-precision number by forcing its format pattern onto the decimal part. You can bypass this behavior with the quantization parameter:

format_percent(23.9876, locale='en_US')
# => '2,399%'

format_percent(23.9876, locale='en_US', quantization=False)
# => '2,398.76%'

Raises:

  • If the numbering system is not supported by the locale.

format_scientific

Formats a number in scientific notation following the locale's formatting rules.

format_scientific(
    number: float | decimal.Decimal | str,
    *,
    format: str | None = None,
    quantization: bool = True,
    numbering_system: str = 'latn',
    locale: str = 'en'
) -> str
Argument Description
number The number to format in scientific notation.
format The format string to use.
quantization Truncate and round high-precision numbers to the format pattern. Defaults to True.
numbering_system The numbering system used for formatting number symbols. Defaults to "latn".
The special value "default" will use the default numbering system of the locale.
locale Force the locale to use for formatting.
format_scientific(10_000, locale='en_US')
# => '1E4'

format_scientific(10_000, locale='ar_EG', numbering_system='default')
# => '1أس4'

The format pattern can also be specified explicitly:

format_scientific(1_234_567, format='##0.##E00', locale='en_US')
# => '1.23E06'

By default the locale is allowed to truncate and round a high-precision number by forcing its format pattern onto the decimal part. You can bypass this behavior with the quantization parameter:

format_scientific(1_234.9876, format='#.##E0', locale='en_US')
# => '1.23E3'

format_scientific(1_234.9876, format='#.##E0', locale='en_US', quantization=False)
# => '1.2349876E3'

Raises:

  • If the numbering system is not supported by the locale.

format_size

Format a byte count as a human-readable string with binary (1024) units.

format_size(
    number: str | int | float | decimal.Decimal | None,
    *,
    precision: int = 3,
    significant: bool = True,
    strip_zeros: bool = True,
    round_mode: str = 'default',
    locale: str = 'en'
) -> str
Argument Description
number the byte count to format.
precision the number of significant digits to include.
significant If True, precision is the number of significant digits.
If False, it's the number of fractional digits (defaults to True).
strip_zeros whether to remove trailing zeros after the decimal point.
round_mode how to round the number; must be one of ["up", "down", "half_up",
"half_down", "half_even", "ceiling, "floor, "default"].
locale force the locale to use for formatting.
format_size(120)
# => '120 Bytes'

format_size(1024)
# => '1 KB'

format_size(15_678)
# => '15.3 KB'

format_size(133_235_678)
# => '127 MB'

format_size(133_235_678, precision=5)
# => '127.06 MB'

format_size(133_235_678, precision=5, locale="de")
# => '127,06 MB'

format_list

Format the items in lst as a list.

format_list(
    lst: 'Sequence[str]',
    *,
    style: Literal['standard', 'standard-short', 'or', 'or-short', 'unit', 'unit-short', 'unit-narrow'] = 'standard',
    locale: str = 'en'
) -> 'Sequence[str]'
Argument Description
lst A sequence of items to format in to a list
style The style to format the list with.
locale Force the locale to use for formatting.
format_list(['apples', 'oranges', 'pears'], locale='en')
# => 'apples, oranges, and pears'

format_list(['apples', 'oranges', 'pears'], locale='zh')
# => 'apples、oranges和pears'

format_list(['omena', 'peruna', 'aplari'], style='or', locale='fi')
# => 'omena, peruna tai aplari'

Not all styles are necessarily available in all locales. The function will attempt to fall back to replacement styles according to the rules set forth in the CLDR root XML file, and raise a ValueError if no suitable replacement can be found.

Avaliable styles (from the Unicode TR35-49 spec 1):

standard
A typical 'and' list for arbitrary placeholders. eg. "January, February, and March"
standard-short
A short version of an 'and' list, suitable for use with short or abbreviated placeholder values. eg. "Jan., Feb., and Mar."
or
A typical 'or' list for arbitrary placeholders. eg. "January, February, or March"
or-short
A short version of an 'or' list. eg. "Jan., Feb., or Mar."
unit
A list suitable for wide units. eg. "3 feet, 7 inches"
unit-short
A list suitable for short units eg. "3 ft, 7 in"
unit-narrow
A list suitable for narrow units, where space on the screen is very limited. eg. "3′ 7″"

Not all styles are necessarily available in all locales.


truncate

Truncate a string to a specified length.

truncate(
    value: str,
    length: int = 255,
    killwords: bool = False,
    end: str = '...',
    leeway: int = 4
) -> str
Argument Description
value The string to truncate
length The maximum length of the returned string, including the end string if
truncation occurs
killwords Whether to cut the text at length, or discard the last word
end The string to append if truncation occurs
leeway The tolerance margin for truncation. Strings that only exceed the length by this
amount will not be truncated.

The length is specified with the second parameter (length) which defaults to 255. If the third parameter (killwords) is True the filter will cut the text at length. Otherwise it will discard the last word.

If the text was in fact truncated it will append an ellipsis sign ("..."). You can specify a different sign using the fourth (end) parameter.

Strings that only exceed the length by the tolerance margin given in the fifth (leeway) parameter will not be truncated.

truncate("foo bar baz qux", 9) }}
# -> "foo..."

truncate("foo bar baz qux", 9, True) }}
# -> "foo ba..."

truncate("foo bar baz qux", 11) }}
# -> "foo bar baz qux"

truncate("foo bar baz qux", 11, False, '...', 0) }}
# -> "foo bar..."

url_for

Builds a URL for the route with the given name, filling in placeholders with the given kwargs or with attributes of the given object.

url_for(
    name: str,
    object: Any = None,
    *,
    _anchor: str = '',
    _full: bool = False,
    **kw
) -> str
Argument Description
name The name of the route to build the URL for. This is usually the
qualified name of the to method minus the "Controller" suffix,
eg: Page.show, but it can be any unique string if you set the
name argument when declaring the route.
object Optional. An object to fill in the placeholders of the route.
For each placeholder, the router will look for a matching key in
kw first, then for an attribute with the same name in the object,
and then for an attribute with the same name but without the controller
prefix (e.g. for ItemController, the placeholder :item_id will look
for item_id and then id in the object attributes).
_anchor Optional. If given, appends an anchor to the URL (e.g. #section1).
_full Optional. If True, builds a full URL including the protocol and host.
The host is determined by the route's host constraint if it has one,
or by the application's default host otherwise.
**kw Additional keyword arguments to fill in the placeholders of the route.
These take precedence over the attributes of the given object.
url_for("Page.show", object=page)
# => "/pages/123"

url_for("Page.show", page_id=123, _anchor="section1")
# => "/pages/123#section1"

# The host is determined by the route's host constraint
# or by the application's default host.
url_for("Page.show", page_id=123, _full=True)
# => "http://www.example.com/pages/123#section1"

url_is

Tells if the URL for the given route name and parameters is the same as the current URL as reported by current.request.path (ignoring trailing slashes and anchors). This is useful for things like active links in navigation bars.

url_is(
    name: str,
    object: Any = None,
    *,
    curr_url: str = '',
    **kw
) -> bool
Argument Description
name The name of the route to build the URL for. This is usually the
qualified name of the to method minus the "Controller" suffix,
eg: Page.show, but it can be any unique string if you set the name
argument when declaring the route.
object Optional. An object to fill in the placeholders of the route.
For each placeholder, the router will look for a matching key in
kw first, then for an attribute with the same name in the object,
and then for an attribute with the same name but without the controller
prefix (e.g. for ItemController, the placeholder :item_id will look
for item_id and then id in the object attributes).
curr_url Optional. The URL to compare to.

If a current URL is not given, it defaults to current.request.path. This is useful if you want to compare to a different URL than the current request's path, for example when you are building a link to a section in the same page and want to compare

url_is("Page.show", page_id=123, curr_url="/pages/123#section1")
# => True

url_is("Page.show", page_id=123, curr_url="/pages")
# => False

url_startswith

Tells if the URL for the given route name and parameters starts with the current URL as reported by current.request.path (ignoring trailing slashes and anchors). This is useful for things like active links to sections in navigation bars.

url_startswith(
    name: str,
    object: Any = None,
    *,
    curr_url: str = '',
    **kw
) -> bool
url_startswith("Page.show", page_id=123, curr_url="/pages/123#section1")
# => True

url_startswith("Page.show", page_id=123, curr_url="/pages/")
# => True

url_startswith

Tells if the URL for the given route name and parameters starts with the current URL as reported by current.request.path (ignoring trailing slashes and anchors). This is useful for things like active links to sections in navigation bars.

url_startswith(
    name: str,
    object: Any = None,
    *,
    curr_url: str = '',
    **kw
) -> bool
url_startswith("Page.show", page_id=123, curr_url="/pages/123#section1")
# => True

url_startswith("Page.show", page_id=123, curr_url="/pages/")
# => True

dom_id

Generate a stable id for an object, suitable for use in HTML element ids.

dom_id(
    obj: Any,
    prefix: str = ''
) -> str
Argument Description
obj The object to generate a DOM id for. Can be a model instance or a class.
prefix An optional string to prefix the id with, for namespacing.

It uses the object's class name and primary key (if available) to generate a unique id. If there is no primary key, prefix with “new_” instead.

dom_id(Post.get(45))   # => "post_45"
dom_id(Post.create())  # => "new_post"

The prefix argument can be used to add a namespace to the id, for example:

dom_id(Post.get(45), "edit")  # => "edit_post_45"

If the object has a to_key() method, it will be used to get the key instead of the primary key. This allows you to customize the key generation for privacy-sensitive or more complex models.

If the object is a class rather than an instance, only the class name is used:

dom_id(Post)            # => "post"
dom_id(Post, "custom")  # => "custom_post"

render_css

Uses the collect_css() list to generate an HTML fragment with <link rel="stylesheet" href="{url}"> tags.

render_css() -> markupsafe.Markup

render_js

Uses the collect_js() list to generate an HTML fragment with <script type="module" src="{url}"></script> tags.

render_js(
    module: bool = True,
    defer: bool = True
) -> markupsafe.Markup
Argument Description
module Whether to render the script tags as modules, e.g.:
<script type="module" src="..."></script>
defer Whether to add the defer attribute to the script tags,
if module is False (all module scripts are also deferred), e.g.:
<script src="..." defer></script>

render_assets

Calls assets.render_css() and assets.render_js() to generate an HTML fragment with <link rel="stylesheet" href="{url}"> and <script type="module" src="{url}"></script> tags.

render_assets(
    module: bool = True,
    defer: bool = True
) -> markupsafe.Markup
Argument Description
module Whether to render the script tags as modules, e.g.:
<script type="module" src="..."></script>
defer Whether to add the defer attribute to the script tags,
if module is False (all module scripts are also deferred), e.g.:
<script src="..." defer></script>

collect_css

Returns a list of CSS files for the component and its children.

collect_css(
    _visited: set[str] | None = None
) -> list[str]

collect_js

Returns a list of JS files for the component and its children.

collect_js(
    _visited: set[str] | None = None
) -> list[str]

render_importmap

Render a script tag containing the import map for the app's assets.

render_importmap(_app) -> str

An import map is a JSON object that maps module specifiers to URLs, allowing you to use bare module specifiers in your JavaScript code. For example, with the following import map:

```html
<script type="importmap">
{
    "imports": {
        "my-lib": "/static/my-lib.js"
    }
}
</script>
```

You can import `my-lib` in your JavaScript code like this:

```javascript import from "my-lib"; ```

The `render_importmap` function generates a script tag with the import map based on
the app's configuration. It looks for an `IMPORT_MAP` configuration variable, which
should be a dictionary mapping module specifiers to asset paths or URLs.