Docma Jinja Rendering¶
The rendering phase uses Jinja to render HTML content with the parameters provided at run-time. Other components (e.g. query specifications) also use Jinja rendering on some of their content.
Note
The docma Jinja subsystem has been refactored somewhat in v2.2.0.
All of the facilities provided by Jinja are available, including parameter
injection, loops, conditional content and use of the include directive to
incorporate other content from the document template. Include directives should
use the name of the file relative to the template root. e.g.
{% include 'my-file.html' %}
See also Jinja Rendering Parameters Provided by Docma.
In addition to standard Jinja facilities, docma also provides a number of extra filters and extensions.
Rendering Parameters¶
The parameters used by docma during the template rendering process is the union of the following (from highest to lowest precedence):
-
Parameters supplied by the user at run-time.
-
Parameters specified under
parameters->defaultsin the template configuration file
Parameters are any object that can be represented in JSON / standard YAML, which can include arbitrary combinations of objects, lists and scalar values.
The marshalling process deep-merges the parameter trees from each source. Lists are not merged. One list will replace another if they occur at the same location.
Rendering Parameters Provided by Docma¶
In addition to user supplied parameters, docma includes the following items
under the docma key.
| Key | Notes | Description |
|---|---|---|
| calendar | The Python calendar module. |
|
| data | Function to invoke a docma data provider and return the data as a list of dictionaries. See Data Source Specifications for HTML Rendering. | |
| datetime | The Python datetime module. |
|
| format | The format of the output document to be produced, PDF or HTML. This can be used, among other things, for format specific content or formatting (e.g. CSS variations). |
|
| paramstyle | (1) | Corresponds to the DBAPI 2.0 paramstyle attribute of the underlying database driver when processing a query specification. |
| template | An object containing information about the document template. | |
| --> description | The description field from the template configuration file. |
|
| --> doc_no | (2) | The document number in the list being included in the final document, starting at 1. |
| --> document | (2) | The path for the source document being processed. This is a pathlib Path() instance. |
| --> id | The id field from the template configuration file. |
|
| --> overlay_id | (3) | The ID of the current overlay set being rendered. |
| --> overlay_path | (3) | The path for the current overlay file being rendered. This is a pathlib Path() instance. |
| --> page | (2) | The starting page number for the current document with respect to the final output document. This may be useful for manipulating page numbering in multipart documents. Or not. |
| --> version | The version field from the template configuration file. |
|
| version | The docma version. |
Notes
- The
paramstyleparameter is only available for use in query specifications. -
The
template.doc_no,template.documentandtemplate.pageparameters are only available when a document file is being rendered (i.e. not when an overlay is being rendered). Thetemplate.pageparameter is only available for PDF outputs. -
The
template.overlay_idandtemplate.overlay_pathparameters are only available when an overlay file is being rendered.
For example, to insert today's date:
{{ docma.datetime.date.today() | date }} -- "date" filter formats for locale
To check whether we are producing HTML or PDF:
This is {{ docma.format }} output using **docma** version {{ docma.version }}.
Docma Jinja Filters¶
Note
Jinja filter management has changed significantly in docma 2.2. Some filters have been renamed (with backward compatible aliases) and a new, more extensible filter plugin system has been implemented.
In addition to the standard filters provided by Jinja, docma provides a number of additions. These are divided into:
Info
Custom filter names are not case sensitive.
Generic Filters¶
Filters marked with * are locale aware.
| Filter Name | Description |
|---|---|
| compact_decimal * | Format a number in a compact format. |
| css_id | Sanitise a string to be a valid CSS identifier. |
| currency * | Format currency. |
| date * | Format a date. |
| datetime * | Format a datetime. |
| decimal * | Format a number. |
| dollars | Legacy. Format currency a value as dollars. |
| parse_date * | Parse a date string into a datetime.date instance. |
| parse_time * | Parse a date string into a datetime.time instance. |
| percent * | Format a percentage. |
| phone * | Format a phone number. |
| require | Abort with an error message an expression does not have a truthy value. |
| sql_safe | Ensure that a string value is safe to use in SQL and generate an error if not. |
| time * | Format a time value. |
| timedelta * | Format a timedelta value. |
Regional Filters¶
| Filter Name | Description |
|---|---|
| abn | Deprecated. Use au.abn. |
| acn | Deprecated. Use au.abn. |
| au.abn | Format an Australian Business Number (ABN). |
| au.acn | Format an Australian Company Number (ACN). |
Jinja Filter: au.abn¶
Format an Australian Business Number (ABN).
This supersedes the, now deprecated, abn filter.
Filter Signature
au.abn(value: str) -> str
Example
{{ '51824753556' | au.abn }} --> 51 824 753 556
Jinja Filter: au.acn¶
Format an Australian Company Number (ACN). This supersedes the, now deprecated,
acn filter.
Filter Signature
au.acn(value: str) -> str
Example
{{ '123456789' | au.acn }} --> 123 456 789
Jinja Filter: compact_decimal¶
Format numeric values.
This is a locale-aware filter that provides an interface to the Babel format_compact_decimal() API. All of its parameters can be used in the filter to obtain fine-grained control over formatting.
The locale is determined as described in Locale in Docma
Templates. It can also be specified explicitly by
adding a locale argument to the filter.
Filter Signature
compact_decimal(
value: str | int | float,
*args,
rounding: str = 'half-up',
default: int | float | str | None = None,
**kwargs
) -> str
| Parameter | Description |
|---|---|
| value | Filter input value. Numbers and strings containing numbers are accepted. |
| *args | Passed to Babel's format_compact_decimal(). |
| rounding | How to round the value. This must be one of the rounding modes in Babel's decimal.ROUND_*, with the ROUND_ prefix removed. Case is ignored and hyphens become underscores. Defaults to half-up (Excel style rounding), instead of half-even (Bankers rounding) which is Python's normal default. |
| default | The default value to use for the filter if the input value is empty (i.e. None or an empty string). If the input value is empty and default is a string, it is used as-is as the return value of the filter. If the input value is empty, and default is not specified, an error is raised. Otherwise, the default is assumed to be numeric and is used as the input to the filter. Note: The default parameter does something different to the Jinja standard default filter. They are both useful but not interchangeable. |
| **kwargs | Passed to Babel's format_compact_decimal(). This includes the option of using the locale parameter to specify locale. |
Examples
Assuming locale is set to en_AU:
{{ 1234.5678 | compact_decimal }} --> 1K
{{ '1234.5678' | compact_decimal }} --> 1K
Locale can be specified explicitly, if required:
{{ 1234.5678 | compact decimal(locale='fr_FR') }} --> 1 k
Jinja Filter: css_id¶
Sanitise a string to be a valid CSS identifier.
!!! "Filter Signature"
```python
css_id(value: str) -> str
```
Example
{{ 'a/()=*&bcd'' | css_id }} --> abcd
Jinja Filter: currency¶
Format a currency value.
This is a locale-aware filter that provides an interface to the Babel format_currency() API.
It is important to understand that there are two orthogonal aspects to formatting currency values:
-
The currency involved, such as Australian dollars (AUD), Euros (EUR) etc.
-
The locale in which the currency is to be presented.
For example:
- One Australian dollar would appear in Australia as
$1.00. - One Australian dollar would appear in the US as
A$1.00 - One Australian dollar would appear in France as
1,00 AU$
For the docma filter, the currency (AUD in the example above) can be specified in one of two ways:
- By providing an argument to the currency filter
{{ 1 | currency('AUD') }}; or - Using the currency name itself as an alias for the filter name
{{ 1 | AUD }}. Docma dynamically generates a filter alias for known currencies. Case is not significant.
The locale is determined as described in Locale in Docma
Templates. It can also be specified explicitly by
adding a locale argument to the filter.
Filter Signature
currency(
value: str | int | float,
currency: str,
*args,
rounding: str = 'half-up',
default: int | float | str | None = None,
**kwargs
) -> str
... or ....
<CURRENCY_CODE>(
value: str | int | float,
*args,
rounding: str = 'half-up',
default: int | float | str | None = None,
**kwargs
) -> str
Here <CURRENCY_CODE> can be AUD, GBP, EUR etc.
| Parameter | Description |
|---|---|
| value | Filter input value. Numbers and strings containing numbers are accepted. Jinja will inject this automatically. |
| currency | The currency code (e.g AUD, EUR etc.) |
| *args | Passed to Babel's format_currency(). |
| rounding | How to round the value. This must be one of the rounding modes in Babel's decimal.ROUND_*, with the ROUND_ prefix removed. Case is ignored and hyphens become underscores. Defaults to half-up (Excel style rounding), instead of half-even (Bankers rounding) which is Python's normal default. |
| default | The default value to use for the filter if the input value is empty (i.e. None or an empty string but not zero). If the input value is empty and default is a string, it is used as-is as the return value of the filter. If the input value is empty, and default is not specified, an error is raised. Otherwise, the default is assumed to be numeric and is used as the input to the filter. Note: The default parameter does something different to the Jinja standard default filter. They are both useful but not interchangeable. |
| **kwargs | Passed to Babel's format_decimal(). This includes the option of using the locale parameter to specify locale. |
Examples
Assuming locale is set to en_AU:
{{ 123 | AUD }} --> $123.00
{{ 123 | currency('AUD') }} --> $123.00
{{ '123' | NZD }} --> NZD123.00 (numeric strings are fine as input)
{{ None | AUD }} --> ERROR!
{{ None | AUD(default=0) }} --> $0.00
{{ None | AUD(default='FREE!')}} --> FREE!
{{ -123 | AUD(format="¤#,###;(¤#)", currency_digits=False)}} --> ($123)
Locale can be specified explicitly, if required:
{{ 123 | EUR(locale='en_GB') }} --> €123.00
{{ 123 | EUR(locale='fr_FR' }} --> 123,00 €
The legacy dollars filter can be replicated like so (use whatever dollar currency is appropriate):
{{ 1234.5 | dollars }} --> {{ 1234.5 | AUD }} --> $1,234.50
{{ 1234.5 | dollars(0) }} --> {{ AUD(format="¤#,###", currency_digits=False) }} --> $1,235
Jinja Filter: date¶
Format date values.
This is a locale-aware filter that provides an interface to the Babel format_date() API. All of its parameters can be used in the filter to obtain fine-grained control over formatting.
The locale is determined as described in Locale in Docma
Templates. It can also be specified explicitly by
adding a locale argument to the filter.
Filter Signature
date(value: datetime.date | datetime.datetime, *args, **kwargs) --> str
| Parameter | Description |
|---|---|
| value | Filter input value. This must be a datetime.date or datetime.datetime instance. |
| *args | Passed to Babel's format_date(). |
| **kwargs | Passed to Babel's format_date(). This includes the option of using the locale parameter to specify locale. |
Examples
Assuming locale is set to en_AU:
{% set value = docma.datetime.date(2025, 9, 17) %}
{{ value | date }} --> 17 Sept 2025 (medium format is the default)
{{ value | date(format='short') }} --> 17/9/25
{{ value | date(format='long') }} --> 17 September 2025
{{ value | date(format='full') }} --> Wednesday, 17 September 2025
{{ value | date(format='dd/MM/yyyy')}} --> 17/09/2025
Locale can be specified explicitly, if required:
{{ value | datetime(locale='en_US') }} --> Sep 17, 2025
If date strings need to be handled, they will need to be converted to a Python
datetime.date
instance first. For date strings guaranteed to be in ISO 8601 format, Python's
standard datetime.date.fromisoformat() is fine. Otherwise, the safest way to
do this for dates containing only numbers (no month names) is to use the
parse_date filter as this is docma locale aware,
unlike the Python standard datetime.datetime.strptime().
Examples
{{ docma.datetime.date.fromisoformat('2025-09-1') | date }} --> 1 Sept 2025
{{ '1/9/2025' | parse_date | date }} --> 1 Sept 2025
{{ '1/9/2025' | parse_date(locale='en_US') | date }} --> 9 Jan 2025
You are in a maze of twisty little passages, all alike ...
There is no fully reliable way to parse arbitrary dates containing month names in a generic, locale-aware away. Don't be tempted to attempt this in a docma template. If you think you need to, you are either solving the problem the wrong way or solving the wrong problem.
Jinja Filter: datetime¶
Format datetime values.
This is a locale-aware filter that provides an interface to the Babel format_datetime() API. All of its parameters can be used in the filter to obtain fine-grained control over formatting.
The locale is determined as described in Locale in Docma
Templates. It can also be specified explicitly by
adding a locale argument to the filter.
The filter signature is:
Filter Signature
datetime(value: datetime.date | datetime.datetime | datetime.time, *args, **kwargs) -> str
| Parameter | Description |
|---|---|
| value | Filter input value. Typically, this would be a datetime.datetime instance. While datetime.date and datetime.time instances are also accepted, they are unlikely to be particularly useful. |
| *args | Passed to Babel's format_datetime(). |
| **kwargs | Passed to Babel's format_datetime(). This includes the option of using the locale parameter to specify locale. |
Examples
Assuming locale is set to en_AU:
{% set value = docma.datetime.datetime(2025, 9, 17, 14, 15, 16) %}
{{ value | datetime }} --> 17 Sept 2025, 2:15:16 pm
Locale can be specified explicitly, if required:
{{ value | datetime(locale='en_US') }} --> Sep 17, 2025, 2:15:16 PM
If datetime strings need to be handled, they will need to be converted to a
Python
datetime.datetime
instance first. For datetime strings guaranteed to be in ISO 8601 format,
Python's standard datetime.datetime.fromisoformat() is fine.
Example
{{ docma.datetime.datetime.fromisoformat('2025-09-17T14:15:16') | datetime }}
Tip
Avoid using the Python standard datetime.datetime strptime() if at all
possible. This will use the platform locale and cannot handle the docma
locale. The results can be very unpredictable.
Jinja Filter: decimal¶
Format numeric values.
This is a locale-aware filter that provides an interface to the Babel format_decimal() API. All of its parameters can be used in the filter to obtain fine-grained control over formatting.
The locale is determined as described in Locale in Docma
Templates. It can also be explicitly specified by
adding a locale argument to the filter.
Filter Signature
decimal(
value: str | int | float,
*args,
rounding: str = 'half-up',
default: int | float | str | None = None,
**kwargs
) -> str
| Parameter | Description |
|---|---|
| value | Filter input value. Numbers and strings containing numbers are accepted. |
| *args | Passed to Babel's format_decimal(). |
| rounding | How to round the value. This must be one of the rounding modes in Babel's decimal.ROUND_*, with the ROUND_ prefix removed. Case is ignored and hyphens become underscores. Defaults to half-up (Excel style rounding), instead of half-even (Bankers rounding) which is Python's normal default. |
| default | The default value to use for the filter if the input value is empty (i.e. None or an empty string, but not zero). If the input value is empty and default is a string, it is used as-is as the return value of the filter. If the input value is empty, and default is not specified, an error is raised. Otherwise, the default is assumed to be numeric and is used as the input to the filter. Note: The default parameter does something different to the Jinja standard default filter. They are both useful but not interchangeable. |
| **kwargs | Passed to Babel's format_decimal(). This includes the option of using the locale parameter to specify locale. |
Examples
Assuming locale is set to en_AU:
{{ 1234.5678 | decimal }} --> 1,234.568 (Default is to round to 3 decimal places)
{{ '1234.5678' | decimal }} --> 1,234.568 (numeric strings are fine as input)
{{ None | decimal }} --> ERROR!
{{ None | decimal(default=0) }} --> 0
{{ None | decimal(default='nix')}} --> nix
Locale can be specified explicitly, if required:
{{ 1234.5678 | decimal(locale='fr_FR') }} --> 1 234,568
Jinja Filter: dollars¶
Round and format a currency value as dollars.
Banker's half-up, rounding is used (like Excel) instead of the half-even rounding that is Python's normal default.
This filter is a legacy that is not actually deprecated (yet), but its use is discouraged. Use the currency filter in preference.
Filter Signature
dollars(value: str | int | float, precision: int = 2, symbol: str = '$') -> str
| Parameter | Description |
|---|---|
| value | A number or numeric string. |
| precision | Number of decimal places to show. Defaults to 2. |
| symbol | The currency symbol to show. Defaults to $. |
Examples
{{ 1234.50 | dollars }} --> $1,234.50
{{ 1234.50 | dollars(0) }} --> $1,235
Jinja Filter: parse_date¶
Parse a date string into a datetime.date instance.
This is a locale-aware filter that provides an interface to the Babel parse_date() API.
Filter Signature
parse_date(value: str, *args, **kwargs) -> datetime.date
| Parameter | Description |
|---|---|
| value | Filter input value. The parser understands component ordering variations by locale but cannot handle month names. Numbers only. |
| *args | Passed to Babel's parse_date(). |
| **kwargs | Passed to Babel's parse_date(). This includes the option of using the locale parameter to specify locale. |
Examples
Assuming locale is set to en_AU:
{{ '1/9/2025' | parse_date) }} --> datetime.date(2025, 9, 1)
Locale can be specified explicitly, if required:
{{ '1/9/2025' | parse_date(locale='en_US') }} --> datetime.date(2025, 1, 9)
Jinja Filter: parse_time¶
Parse a date string into a datetime.time instance.
This is a locale-aware filter that provides an interface to the Babel parse_time() API.
Filter Signature
parse_time(value: str, *args, **kwargs) -> datetime.time
| Parameter | Description |
|---|---|
| value | Filter input value. |
| *args | Passed to Babel's parse_time(). |
| **kwargs | Passed to Babel's parse_time(). This includes the option of using the locale parameter to specify locale. |
Examples
Assuming locale is set to en_AU:
{{ '2:15 pm' | parse_time) }} --> datetime.time(14, 15)
Locale can be specified explicitly, if required:
{{ '1/9/2025' | parse_date(locale='en_US') }} --> datetime.date(2025, 1, 9)
Jinja Filter: percent¶
Format percentage values.
This is a locale-aware filter that provides an interface to the Babel format_percent() API. All of its parameters can be used in the filter to obtain fine-grained control over formatting.
The locale is determined as described in Locale in Docma
Templates. It can also be specified explicitly by
adding a locale argument to the filter.
Filter Signature
percent(
value: str | int | float,
*args,
rounding: str = 'half-up',
default: int | float | str | None = None,
**kwargs
) -> str
| Parameter | Description |
|---|---|
| value | Filter input value. Numbers and strings containing numbers are accepted. |
| *args | Passed to Babel's format_percent(). |
| rounding | How to round the value. This must be one of the rounding modes in Babel's decimal.ROUND_*, with the ROUND_ prefix removed. Case is ignored and hyphens become underscores. Defaults to half-up (Excel style rounding), instead of half-even (Bankers rounding) which is Python's normal default. |
| default | The default value to use for the filter if the input value is empty (i.e. None or an empty string). If the input value is empty and default is a string, it is used as-is as the return value of the filter. If the input value is empty, and default is not specified, an error is raised. Otherwise, the default is assumed to be numeric and is used as the input to the filter. Note: The default parameter does something different to the Jinja standard default filter. They are both useful but not interchangeable. |
| **kwargs | Passed to Babel's format_percent(). This includes the option of using the locale parameter to specify locale. |
Examples
Assuming locale is set to en_AU:
{{ 0.1234 | percent }} --> 12%
{{ '0.1234' | percent }} --> 12%
{{ None | percent }} --> ERROR!
{{ None | percent(default=0) }} --> 0%
{{ None | percent(default='--')}} --> --
Locale can be specified explicitly, if required:
{{ '0.123' | percent(locale='fr_FR') }} --> 12 %
Jinja Filter: phone¶
Format phone numbers. If a number cannot be formatted, the unmodified input is returned.
This is a locale-aware filter.
The underlying process is implemented using the excellent Python phonenumbers package, which is itself a port of Google's libphonenumber library.
Phone number formatting varies substantially internationally. Hence, the filter needs to determine the relevant region for each phone number. It can do that in one of 3 ways (highest precedence to lowest)
-
An international code in the source phone number.
-
An explicit region code argument to the phone filter (expressed as a two-character ISO country code).
-
By assuming the phone number is associated with the effective locale setting For example, a locale setting of
en_AUwould imply the number is part of the Australian phone numbering plan.
Filter Signature
phone(number: str, region: str = None, *, format: str = None) -> str
| Parameter | Description |
|---|---|
| number | The phone number input to the filter. Phone numbers are always strings, never integers. Ever. |
| region | The region to which the phone number belongs as a 2 character ISO country code. Ignored if the phone number includes an international code. If not specified, the country code from the current effective locale is used. |
| format | See below. |
Phone numbers can be formatted in different ways. The following values of the format parameter are supported:
| Format | Description |
|---|---|
| E164 | E.164 is the standard International Telecommunication Union (ITU) format for worldwide telephone numbers. e.g. +61491570006 |
| INTERNATIONAL | The full international phone number, formatted as per national conventions. e.g. +61 491 570 006 |
| NATIONAL | The national number component of the phone number without the international code component, formatted as per national conventions. e.g. 0491 570 006 |
| RFC3966 | The URI format for phone numbers. This will typically generate one-touch call links in on-line content. e.g. tel:+61-491-570-006 |
If not specified, NATIONAL is used if the region for the phone number matches
that for the current locale and INTERNATIONAL otherwise.
Examples
Assuming locale is set to en_AU:
{{ '0491 570 006' | phone }} --> 0491 570 006 (Locale will provide "AU" as region)
{{ '+61 491 570 006' | phone }} --> 0491 570 006 (Region comes from the number)
{{ '4155550132' | phone('US') }} --> +1 415-555-0132
{{ '4155550132'| phone('US', format='NATIONAL') }} --> (415) 555-0132
{{ '4155550132'| phone('US', format='RFC3966') }} --> tel:+1-415-555-0132
{{ 'bad-to-the-phone' }} --> bad-to-the-phone (If all else fails, return the input)
Jinja Filter: require¶
Abort with an error message if the value is not a truthy value (i.e. a non-empty string, non-zero integer etc), otherwise return the value.
This is useful for situations where it is better to abort if an expression is expected to have a value, but doesn't, rather than make assumptions.
Filter Signature
require(value: Any) -> Any
Example
Dear Bob,
Your flight details have changed and your flight will now depart at
{{ flight_time | require('flight_time must be a non-empty string') }}.
Don't be late.
Jinja Filter: sql_safe¶
Ensure that a string value is safe to use in SQL and generate an error if not.
This is primarily for use in query specifications to avoid SQL injection. It has a puritanical view on safety but will cover most normal requirements.
Filter Signature
sql_safe(value: str) -> str
Example
SELECT * from {{ table | sql_safe }} ...
Jinja Filter: time¶
Format time values.
This is a locale-aware filter that provides an interface to the Babel format_time() API. All of its parameters can be used in the filter to obtain fine-grained control over formatting.
The locale is determined as described in Locale in Docma
Templates. It can also be specified explicitly by
adding a locale argument to the filter.
Filter Signature
time(value: datetime.time | datetime.datetime, *args, **kwargs) -> str
| Parameter | Description |
|---|---|
| value | Filter input value. This must be a datetime.time or datetime.datetime instance. |
| *args | Passed to Babel's format_time(). |
| **kwargs | Passed to Babel's format_time(). This includes the option of using the locale parameter to specify locale. |
Examples
Assuming locale is set to en_AU:
{% set value = docma.datetime.time(14, 15) %}
{{ value | time }} --> 2:15:00 pm
Locale can be specified explicitly, if required:
{{ value | datetime(locale='de_DE') }} --> 14:15:00
If time strings need to be handled, they will need to be converted to a Python datetime.time instance first. The safest way to do this is to use the parse_time filter as this is docma locale aware.
{{ '14:15' | parse_time | time }} --> 2:15:00 pm
{{ '2:15 pm' | parse_time | time }} --> 2:15:00 pm
Jinja Filter: timedelta¶
Format timedelta values.
This is a locale-aware filter that provides an interface to the Babel format_timedelta() API. All of its parameters can be used in the filter to obtain fine-grained control over formatting.
The locale is determined as described in Locale in Docma
Templates. It can also be specified explicitly by
adding a locale argument to the filter.
Filter Signature
timedelta(value: datetime.timedelta | datetime.datetime | datetime.time, *args, **kwargs) -> str
| Parameter | Description |
|---|---|
| value | Filter input value. This must be a datetime.timedelta instance. |
| *args | Passed to Babel's format_timedelta(). |
| **kwargs | Passed to Babel's format_timedelta(). This includes the option of using the locale parameter to specify locale. |
Tip
The Babel
format_timedelta()
rounding process is not particularly intuitive on first appearance but makes
sense once you get the hang of it. You may need to experiment with
threshold and granularity arguments to get the desired effect.
Examples
Assuming locale is set to en_AU:
{% set d1 = docma.datetime.datetime(2025, 9, 17, 14, 15, 16) %}
{% set d2 = docma.datetime.datetime(2025, 9, 19, 14, 15, 16) %}
{{ (d2 - d1) | timedelta }} --> 2 days (default format is 'long')
{{ (d2 - d1) | timedelta(format='narrow') }} --> 2d
{{ (d2 - d1) | timedelta(add_direction=True) }} --> in 2 days
Locale can be specified explicitly, if required:
{{ (d2 - d1) | timedelta(locale='uk_UA') }} --> '2 дні'
Docma Jinja Extensions¶
Docma provides some custom Jinja extensions. In Jinja, extensions are invoked using the following syntax:
{% tag [parameters] %}
In addition to the custom extensions described below, docma also provides the following standard Jinja extensions:
Jinja Extension: abort¶
The abort extension forces the rendering process to abort with an exception message. It would typically be used in response to some failed correctness check where it's preferable to fail document production rather than to proceed in error.
For example:
{% if bad_data %}
{% abort 'Fatal error - bad data' %}
{% endif %}
Jinja Extension: dump_params¶
The dump_params extension simply dumps the rendering parameters for debugging purposes. The standard Jinja debug extension does something similar (and a bit more) but much less readably.
Typical usage would be:
<PRE>{% dump_params %}</PRE>
Jinja Extension: global¶
The global extension allows values defined within the Jinja content of a HTML document to be made available when rendering other components in a document template.
For example, the following declares the globals a and b.
{% global a=1, b='Plugh' %}
These can then be accessed, either in the file in which they were declared or in a different HTML document, or a query specification like so:
You are at Y{{ globals.a + 1 }}. A hollow voice says "{{ globals.b }}."
The result will be:
Compare this with the standard Jinja set operation:
{% set a=1 %}
The variable a can only be accessed in the file in which it is defined, or a
file that includes that file. It cannot be accessed in a different HTML
document, or a query specification
Warning
It is important to understand that within the docma rendering phase, the Jinja rendering of the component HTML documents is completed before the generation and injection of dynamic content. This means that only the final value of any global parameter is available during the dynamic content generation phase.
It is not possible to use globals to pass a loop variable from the Jinja rendering of the HTML into the dynamic content generation phase.
Docma Format Checkers¶
Docma includes an extensible set of format checkers. These can be used in two ways:
-
In JSON schema specifications as
formatspecifiers forstringdata elements; and -
As Jinja tests in content that will be Jinja rendered.
The docma provided format checkers are divided into:
All docma provided format checker names are case insensitive.
It is easy to add new format checkers, as required.
Generic Format Checkers¶
| Test Name | Description |
|---|---|
| date.dmy | Date formatted as day/month/year. The separators can be any of /-_. or missing (e.g. 31/12/2024, 31.12.2024, 31-12-2024, 31_12_2024, 31122024). |
| date.mdy | Date formatted as month/day/year. The separators can be any of /-_. or missing (e.g. 12/31/2024, ...). |
| date.ymd | Date formatted as year/month/day. The separators can be any of /-_. or missing (e.g. 2024/12/31, ...). |
| DD/MM/YYYY | JSON Schema use only. Deprecated. Use date.dmy instead. |
| energy_unit | An energy unit (e.g. kWh, MVArh). |
| locale | A locale specifier (e.g. en_AU, fr_FR) |
| power_unit | A power unit (e.g. kW, MVA). |
| semantic_version | A version in the form major.minor.patch (e.g. 1.3.0). |
Regional Format Checkers¶
| Checker Name | Description |
|---|---|
| ACN | Deprecated. Use au.abn instead. |
| ABN | Deprecated. Use au.abn instead. |
| au.ABN | Australian Business Number. |
| au.ACN | Australian Company Number. |
| au.MIRN | Australian energy industry Gas Meter Installation Registration Number. |
| au.NMI | Australian energy industry National Metering Identifier. |
| MIRN | Deprecated. Use au.MIRN instead. |
| NMI | Deprecated. Use au.NMI instead. |
Format Checkers in JSON Schema¶
JSON Schema specifications are supported, and strongly recommended, in a number of docma components, such as as the template configuration file, and query specifications. They provide run-time type checking of important data elements and are an important safety mechanism.
Like the JSON Schema built-in
string formats,
docma provided format checkers can be used in a schema specification with the
format attribute of string objects, like so:
type: object
properies:
prop1:
type: string
# Use a built in format like "email" or one of **docma**'s format checkers
format: ...
Note
Examples are given in YAML rather than JSON for readability, and because they are specified in YAML in docma.
For example, consider a document template for a contract that requires parameters for customer email, contract start date, and customer Australian Business Number (ABN) to be specified: The relevant portion of the template configuration file might look like this:
parameters:
schema:
# Schema for the schema!
$schema: https://json-schema.org/draft/2020-12/schema
title: Parameters validation schema
type: object
required:
- locale
- customer_email
- customer_abn
- contract_start_date
properties:
locale:
type: string
format: locale # This is a docma provided format checker
customer_email:
type: string
format: email # This is a standard JSON schema format checker
customer_abn:
type: string
format: au.ABN # This is a docma provided format checker.
contract_start_date:
type: string
format: date.dmy # This is a docma provided format checker
Docma will validate values provided at run-time against this schema.
Format Checkers in Jinja¶
In addition to the standard tests provided by Jinja, the docma format checkers can also be used as Jinja tests, like so:
{% if contract_date is not date.dmy %}
{% abort 'Bad date' %}
{% endif %}
When used as Jinja tests, none of the docma format checkers accept an arguments additional to the value being checked.
Note
Docma can also be extended with Jinja tests that can accept additional arguments, but these would not also be used in JSON Schema specifications and hence would not be considered to be format checkers.