Special Jinja2 extension for Copier that allows to load extensions using file paths relative to the template root instead of Python dotted paths.
Maintained. Last release 8 weeks ago, commits in 3 of the last 26 weeks. Weaker on commit activity and release cadence.
pip install copier-template-extensionsCopier Template-Extensions
Special Jinja2 extension for Copier that allows to load extensions using file paths relative to the template root instead of Python dotted paths.
Installation
With pip:
pip install copier-template-extensions
With uv:
uv tool install copier --with copier-template-extensions
With pipx:
pipx install copier
pipx inject copier copier-template-extensions
Usage
In your template configuration, first add our loader extension, then add your templates extensions using relative file paths, and the class name after a colon:
_jinja_extensions:
- copier_template_extensions.TemplateExtensionLoader
- extensions/context.py:ContextUpdater
- extensions/slugify.py:SlugifyExtension
With this example, you are supposed to have an extensions
directory at the root of your template containing two modules:
context.py and slugify.py.
📁 template_root
├── 📄 abc.txt.jinja
├── 📄 copier.yml
└── 📁 extensions
├── 📄 context.py
└── 📄 slugify.py
See Context hook extension
to see how the ContextUpdater class can be written.
The SlugifyExtension class could be written like this:
import re
import unicodedata
from jinja2.ext import Extension
# taken from Django
# https://github.com/django/django/blob/main/django/utils/text.py
def slugify(value, allow_unicode=False):
"""
Convert to ASCII if 'allow_unicode' is False. Convert spaces or repeated
dashes to single dashes. Remove characters that aren't alphanumerics,
underscores, or hyphens. Convert to lowercase. Also strip leading and
trailing whitespace, dashes, and underscores.
"""
value = str(value)
if allow_unicode:
value = unicodedata.normalize('NFKC', value)
else:
value = unicodedata.normalize('NFKD', value).encode('ascii', 'ignore').decode('ascii')
value = re.sub(r'[^\w\s-]', '', value.lower())
return re.sub(r'[-\s]+', '-', value).strip('-_')
class SlugifyExtension(Extension):
def __init__(self, environment):
super().__init__(environment)
environment.filters["slugify"] = slugify
