Copier's built-in Jinja2 extension, inspired by Ansible, outsourced for you
Project description
Copier's built-in Jinja2 Extension
Copier's built-in Jinja2 extension, inspired by Ansible, outsourced for you.
Installation
-
With
pip:pip install jinja2-copier-extension
-
With
uv:uv add jinja2-copier-extension
-
With
poetry:poetry add jinja2-copier-extension
-
With
pdm:pdm add jinja2-copier-extension
-
With
pipx(injected into thepipx-managed virtual env of a package):pipx inject PACKAGE jinja2-copier-extension
-
With
uvx(injected into theuvx-managed virtual env of a package):uvx --with jinja2-copier-extension PACKAGE
Usage
Register the extension in your Jinja2 environment to use the provided filters:
from jinja2 import Environment
env = Environment(extensions=["jinja2_copier_extension.CopierExtension"])
# Example:
template = env.from_string("The current time is {{ '%H:%M' | strftime }}")
result = template.render()
print(result)
Filters
The extension provides the following Jinja2 filters:
Base64
b64decode(value: str, encoding: str = "utf-8") → str
Decode a Base64 encoded string.
Example:
Template
{{ 'aGVsbG8gd29ybGQ=' | b64decode }}
Output
"hello world"
b64encode(value: str, encoding: str = "utf-8") → str
Encode a Base64 encoded string.
Example:
Template
{{ 'hello world' | b64encode }}
Output
"YSBzdHJpbmc="
Date/Time
strftime(format: str, second: float | None = None) → str
Convert a Unix timestamp to a date/time string according to a date/time format.
Example:
Template
{{ '%H:%M:%S' | strftime }}
Output
"02:03:04"
to_datetime(string: str, format: str = "%Y-%m-%d %H:%M:%S") → datetime
Convert a string containing date/time information to a datetime object.
Example:
Template
{{ '2016-08-14 20:00:12' | to_datetime }}
Output
datetime.datetime(2016, 8, 14, 20, 0, 12)
Hashing
hash(data: str, algorithm: str = "sha1") → str
Hash data using a configurable algorithm.
Example:
Template
{{ 'hello world' | hash }}
Output
"2aae6c35c94fcfb415dbe95f408b9ce91ee846ed"
md5(data: str) → str
Hash data using the MD5 algorithm.
Example:
Template
{{ 'hello world' | md5 }}
Output
"5eb63bbbe01eeed093cb22bb8f5acdc3"
sha1(data: str) → str
Hash data using the SHA1 algorithm.
Example:
Template
{{ 'hello world' | sha1 }}
Output
"2aae6c35c94fcfb415dbe95f408b9ce91ee846ed"
JSON
from_json(data: str, /, **kwargs: Any) → Any
Deserialize JSON data.
Example:
Template
{% filter from_json %}
{
"name": "Jane",
"age": 30
}
{% endfilter %}
Output
{"name": "Jane", "age": 30}
to_json(obj: Any, /, **kwargs: Any) → str
Serialize an object as JSON.
Example:
Template
{{ {'name': 'Jane', 'age': 30} | to_json }}
Output
{"name": "Jane", "age": 30}
to_nice_json(obj: Any, /, **kwargs: Any) → str
Serialize an object as JSON with nice formatting.
Example:
Template
{{ {'name': 'Jane', 'age': 30} | to_nice_json }}
Output
{
"age": 30,
"name": "Jane"
}
Filesystem
basename(path: str) → str
Get the final component of a path.
Example:
Template
{{ '/etc/asdf/foo.txt' | basename }}
Output
"foo.txt"
dirname(path: str) → str
Get the directory component of a path.
Example:
Template
{{ '/etc/asdf/foo.txt' | basename }}
Output
"/etc/asdf"
expanduser(path: str) → str
Expand a path with the ~ and ~user constructions.
Example:
Template
{{ '~/path/to/foo.txt' | expanduser }}
Output
"/home/<user>/path/to/foo.txt" # Linux
"/Users/<user>/path/to/foo.txt" # macOS
"C:/Users/<user>/path/to/foo.txt" # Windows
expandvars(path: str) → str
Expand a path with the shell variables of form $var and ${var}.
Example:
Template
{{ '$HOME/path/to/foo.txt' | expandvars }}
Output
"/home/<user>/path/to/foo.txt" # Linux
"/Users/<user>/path/to/foo.txt" # macOS
"C:/Users/<user>/path/to/foo.txt" # Windows
fileglob(pattern: str) → list[str]
Get all files in a filesystem subtree according to a glob pattern.
Example:
Filesystem
📁 .
├── 📄 a.txt
├── 📄 b.csv
└── 📁 c
├── 📄 d.txt
└── 📄 e.json
Template
{{ '**/*.txt' | fileglob() | sort }}
Output
["a.txt", "c/d.txt"]
realpath(path: str) → str
Get the canonical form of a path.
Example:
Filesystem
📁 .
└── 📁 a
├── 📁 b
│ └── 📄 foo.txt
└── 📁 c
└── 📄 bar.txt
Template
{{ 'a/c/../b/foo.txt' | realpath }}
Output
"<cwd>/a/b/foo.txt"
splitext(path: str) → tuple[str, str]
Split the extension of a path.
Example:
Template
{{ 'foo.txt' | splitext }}
Output
("foo", ".txt")
win_basename(path: str) → str
Get the final component of a Windows path.
Example:
Template
{{ 'C:/Temp/asdf/foo.txt' | win_basename }}
Output
"foo.txt"
win_dirname(path: str) → str
Get the directory component of a Windows path.
Example:
Template
{{ 'C:/Temp/asdf/foo.txt' | win_dirname }}
Output
"C:/Temp/asdf"
win_splitdrive(path: str) → tuple[str, str]
Split a Windows path into a drive and path.
Example:
Template
{{ 'C:/Temp/asdf/foo.txt' | win_splitdrive }}
Output
("C:", "/Temp/asdf/foo.txt")
Random
shuffle[T](seq: Sequence[T], seed: str | None = None) → list[T]
Shuffle a sequence of elements.
Example:
Template
{{ [1, 2, 3] | shuffle(seed=123) }}
Output
[2, 1, 3]
ans_random[T](stop: int | Sequence[T], start: int = 0, step: int = 0, seed: str | None = None) → int | T
Generate a random integer in a range or choose a random element from a sequence.
Example:
Template
{{ 100 | ans_random(seed='123') }}
Output
93
random_mac(prefix: str, seed: str | None = None) → str
Generate a random MAC address given a prefix.
Example:
Template
{{ '52:54' | random_mac(seed='123') }}
Output
"52:54:25:a4:fc:1f"
Regular expressions
regex_escape(pattern: str, re_type: Literal["python", "posix_basic"] = "python") → str
Escape special characters in a regex pattern string.
Example:
Template
{{ '^a.*b(.+)\c?$' | regex_escape }}
Output
r"\^a\.\*b\(\.\+\)\\c\?\$"
regex_findall(string: str, regex: str, multiline: bool = False, ignorecase: bool = False) → list[str] | list[tuple[str, ...]]
Extract non-overlapping regex matches using re.findall.
Example:
Template
{{ 'foo bar' | regex_findall('[a-z]+') }}
Output
["foo", "bar"]
regex_replace(string: str, pattern: str, replacement: str, ignorecase: bool = False, multiline: bool = False) → str
Substitute non-overlapping regex matches using re.sub.
Example:
Template
{{ 'copier' | regex_replace('^(.*)ier$', '\\1y') }}
Output
"copy"
regex_search(string: str, pattern: str, *args: str, ignorecase: bool = False, multiline: bool = False) → str | list[str] | None
Search a string for a regex match using re.search.
Example:
Template
{{ 'foo/bar' | regex_search('[a-z]+') }}
Output
"foo"
Shell
quote(value: str) → str
Shell-escape a string.
Example:
Template
echo {{ 'hello world' | quote }}
Output
"echo 'hello world'"
Types
bool(value: Any) → bool
Parse anything to boolean.
- Cast to number. Then:
0 → False; anything else→ True. - Find YAML booleans, YAML nulls or
"none"in it and use it appropriately. - Cast to boolean using standard Python
bool(value).
Example:
Template
{{ 'yes' | bool }}
Output
True
type_debug(obj: object) → str
Get the type name of an object.
Example:
Template
{{ 123 | type_debug }}
Output
"int"
Utilities
ans_groupby[V](value: Iterable[V], attribute: str | int) → list[tuple[str | int, list[V]]]
Group a sequence of objects by an attribute.
Example:
Template
{{ [{'name': 'Jane', 'age': 30}, {'name': 'Alice', 'age': 30}, {'name': 'John', 'age': 20}] | ans_groupby('age') }}
Output
[(20, [{"name": "John", "age": 20}]), (30, [{"name": "Jane", "age": 30}, {"name": "Alice", "age": 30}])]
extract(key: Any, container: Any, morekeys: Any | Sequence[Any] | None = None) → Any | Undefined
Extract a value from a container.
Example:
Template
{{ 'k' | extract({'k': 'v'}) }}
Output
"v"
flatten(seq: Sequence[Any], levels: int | None = None) → list[Any]
Flatten nested sequences, filter out None values.
Example:
Template
{{ [1, [None, [2, None, [3]]]] | flatten }}
Output
[1, 2, 3]
mandatory[T](value: T, msg: str | None = None) → T
Require a value to be defined.
Example:
Template
{{ 'foo' | mandatory }}
Output
"foo"
ternary(condition: bool | None, true_val: Any, false_val: Any, none_val: Any = MISSING) → Any
Return a true/false/none value depending on a condition.
Example:
Template
{{ 'true' | ternary('t', 'f') }}
Output
"t"
UUID
to_uuid(name: str) → str
Generate a UUID v5 string from a name.
The UUID namespace is the DNS namespace https://github.com/copier-org/copier.
Example:
Template
{{ 'foo' | to_uuid }}
Output
"faf9357a-ee2a-58ed-94fd-cc8661984561"
YAML
from_yaml(value: str) → Any
Deserialize YAML data.
Example:
Template
{% filter from_yaml %}
name: Jane
age: 30
{% endfilter %}
Output
{"name": "Jane", "age": 30}
from_yaml_all(value: str) → Iterator[Any]
Deserialize multi-document YAML data.
Example:
Template
{% filter from_yaml | list %}
name: Jane
age: 30
---
name: John
age: 20
{% endfilter %}
Output
[{"name": "Jane", "age": 30}, {"name": "John", "age": 20}]
to_yaml(value: Any, /, **kwargs: Any) → str
Serialize data as YAML.
Example:
Template
{{ [{'name': 'Jane', 'age': 30}] | to_yaml }}
Output
- name: Jane
age: 30'
to_nice_yaml(value: Any, /, **kwargs: Any) → str
Serialize data as YAML with nice formatting.
Example:
Template
{{ [{'name': 'Jane', 'age': 30}] | to_nice_yaml }}
Output
- name: Jane
age: 30
Contributions
Contributions are always welcome via filing issues or submitting pull requests. Please check the contribution guide for more details.
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file jinja2_copier_extension-0.2.0.tar.gz.
File metadata
- Download URL: jinja2_copier_extension-0.2.0.tar.gz
- Upload date:
- Size: 13.7 kB
- Tags: Source
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.13.7
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
ef97edcb2187d5a07dc4517e530cbc147857afac57a5d9d004666df120d8d353
|
|
| MD5 |
4339369a4ecb237725a82723fcb2c280
|
|
| BLAKE2b-256 |
06251c80611fcaae29a4e8ed0a5a8be1e1b63846ac86d245312bb4b6df3d4f90
|
Provenance
The following attestation bundles were made for jinja2_copier_extension-0.2.0.tar.gz:
Publisher:
release.yml on copier-org/jinja2-copier-extension
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
jinja2_copier_extension-0.2.0.tar.gz -
Subject digest:
ef97edcb2187d5a07dc4517e530cbc147857afac57a5d9d004666df120d8d353 - Sigstore transparency entry: 711428434
- Sigstore integration time:
-
Permalink:
copier-org/jinja2-copier-extension@a5b32852f7d3634e365b64608ac8ef99260c4c10 -
Branch / Tag:
refs/tags/v0.2.0 - Owner: https://github.com/copier-org
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
release.yml@a5b32852f7d3634e365b64608ac8ef99260c4c10 -
Trigger Event:
release
-
Statement type:
File details
Details for the file jinja2_copier_extension-0.2.0-py3-none-any.whl.
File metadata
- Download URL: jinja2_copier_extension-0.2.0-py3-none-any.whl
- Upload date:
- Size: 18.5 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.13.7
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
8f103cf376e9a1078843d6f8be8caa52c948fd8d3409eab7188bc1c9045e2675
|
|
| MD5 |
71957813d5a9a644dd320764a6f2579c
|
|
| BLAKE2b-256 |
a18a435fc5f347cfde7ee8b95b8b5ed2a2d353e3b4a2b244332b6eef9c68a5c1
|
Provenance
The following attestation bundles were made for jinja2_copier_extension-0.2.0-py3-none-any.whl:
Publisher:
release.yml on copier-org/jinja2-copier-extension
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
jinja2_copier_extension-0.2.0-py3-none-any.whl -
Subject digest:
8f103cf376e9a1078843d6f8be8caa52c948fd8d3409eab7188bc1c9045e2675 - Sigstore transparency entry: 711428445
- Sigstore integration time:
-
Permalink:
copier-org/jinja2-copier-extension@a5b32852f7d3634e365b64608ac8ef99260c4c10 -
Branch / Tag:
refs/tags/v0.2.0 - Owner: https://github.com/copier-org
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
release.yml@a5b32852f7d3634e365b64608ac8ef99260c4c10 -
Trigger Event:
release
-
Statement type: