Skip to main content

Template

Jinja2-based template rendering engine with streaming support for Python.

Overview

VCollab applications render data into various output formats — HTML reports, chart visualizations, CSV exports, styled tables. The rendering logic is always the same: load a template, pass data, produce output.

vcti-template provides a lightweight engine for this pattern. Templates come from three sources — a named registry of strings, the filesystem, or an inline string — all behind one Jinja2 loader, so they share a compiled cache and can {% extends %} or {% include %} each other in any direction. On top of that: streaming for large datasets, a typed exception hierarchy, an autoescape default that configuration cannot weaken, and an optional sandbox.

Installation

pip install vcti-template

# Specific version
pip install vcti-template==2.0.1

Quick Start

Registry + Manager

from vcti.template import TemplateManager, TemplateRegistry

registry = TemplateRegistry()
registry.register("greeting", "Hello, {{ name }}!")
registry.register("row", "<tr><td>{{ value }}</td></tr>")

tm = TemplateManager(registry=registry)
tm.render("greeting", name="World")  # "Hello, World!"

The manager holds a live reference, so templates registered later are picked up on the next render.

Filesystem and Inline

tm = TemplateManager(template_dirs=["./templates"])
tm.render("report.html", title="Q1 Report", data=summary)

tm.render_string("{{ x }} + {{ y }} = {{ x + y }}", x=2, y=3)  # "2 + 3 = 5"

Inline templates are cached by source string, so rendering one in a loop does not recompile it.

Inheritance Across Sources

Either source can extend or include the other; registry entries shadow files of the same name.

registry.register("layout", "<html><body>{% block body %}{% endblock %}</body></html>")
tm = TemplateManager(registry=registry, template_dirs=["./templates"])

# ./templates/invoice.html: {% extends 'layout' %}{% block body %}…{% endblock %}
tm.render("invoice.html", n=1042)

Streaming for Large Data

registry.register("header", "<table><tr><th>Name</th></tr>")
registry.register("footer", "</table>")

chunks = ({"name": row.name} for row in large_dataset.iter_rows())

for fragment in tm.render_streaming(
    "row", chunks, header_template="header", footer_template="footer"
):
    f.write(fragment)

Templates resolve when render_streaming() is called — including everything they include or extend — so a missing one raises there, not partway through after half a file is written. Runtime targets like {% include some_var %} are the exception and still fail during rendering.

Strict Mode

from vcti.template import TemplateRenderError

tm = TemplateManager(strict=True)

try:
    tm.render_string("Hello, {{ name }}!")  # no name provided
except TemplateRenderError as exc:
    print(exc)  # 'name' is undefined

Worth defaulting on for machine-consumed output, where a silently missing value is worse than a loud failure.

Custom Filters and Globals

tm = TemplateManager(
    filters={"shout": lambda s: s.upper() + "!!!"},
    template_globals={"app_name": "MyApp"},
)
tm.render_string("{{ app_name }}: {{ msg|shout }}", msg="hello")  # "MyApp: HELLO!!!"

Custom names take precedence over Jinja2's builtins.

Async Rendering (FastAPI, asyncio)

tm = TemplateManager(registry=registry)

result = await tm.arender("greeting", name="World")

# Not awaited — returns an async iterator, and accepts async iterables
# so chunks can come straight off a cursor.
async for fragment in tm.arender_streaming("row", fetch_rows()):
    await response.write(fragment)

Filters and globals may be coroutines here; they are awaited automatically.

Error Handling

All template-specific errors inherit from TemplateError:

Exception When
TemplateNotFoundError Name not in registry or filesystem, or a missing extends/include target
TemplateSyntaxError Invalid Jinja2 syntax
TemplateRenderError Render failure (e.g., undefined var in strict mode)
TemplateSecurityError Sandbox violation (subclass of TemplateRenderError)

Every Jinja2 failure the engine encounters is mapped onto this hierarchy. An ordinary exception raised by your own filter or global propagates unchanged; one that is itself a jinja2.TemplateError cannot be told apart from the engine's own and arrives as TemplateRenderError.

API Summary

TemplateRegistry

Method Description
register(name, template, *, replace=False) Register a template string
get(name) Retrieve a template string
has(name) Check if name is registered
remove(name) Remove a template
names() List all registered names
templates Immutable view of all templates

TemplateManager

Method Description
render(name, **context) Render a named template
render_string(template, **context) Render an inline template string
render_streaming(name, chunks, ...) Yield rendered fragments per chunk
arender(name, **context) Async render a named template
arender_string(template, **context) Async render an inline template string
arender_streaming(name, chunks, ...) Async yield rendered fragments
Constructor Option Default Description
registry None Template registry instance (held live)
template_dirs None Filesystem directories to search
extra_autoescape_extensions None Extensions to autoescape in addition to the defaults
strict False Raise on undefined variables
sandboxed False Render in Jinja2's sandbox
auto_reload True Re-check templates for changes on every lookup
filters None Custom Jinja2 filters
template_globals None Variables available in all templates

Resolution order for render(): registry → filesystem → error.

Set auto_reload=False in production, where templates do not change while the process runs. It removes a stat() syscall per render, which is a substantial saving for filesystem templates and close to nothing for registry-only ones. The trade is that template edits, replace=True, and remove() stop taking effect for a template already in Jinja2's template cache. That cache is a bounded LRU (400 templates by default), so one evicted under pressure is recompiled from current source and the change appears after all — treat this as a performance option, not a guarantee that templates are frozen.

Security

Autoescaping is on by default and cannot be configuration-disabled. html, htm, xhtml and xml are always escaped, as are inline strings and extensionless registry names; extra_autoescape_extensions only ever widens that set.

Never render untrusted template code. render_string() compiles and executes arbitrary Jinja2 — treat it like eval(). Untrusted input belongs in the context, never in the template source:

registry.register("report", "Hello, {{ user_input }}")

tm.render("report", user_input=request.form["name"])  # SAFE — a context value
tm.render_string(request.form["template"])            # DANGEROUS — run as code

sandboxed=True blocks private-attribute access and unsafe calls if you must render templates you did not author. It narrows the attack surface but is not a guarantee — see SECURITY.md.

Thread Safety

TemplateManager rendering is thread-safe, and one manager can back many concurrent coroutines. TemplateRegistry mutation is not — guard it with a threading.Lock if you register from multiple threads.

Dependencies

  • jinja2>=3.1 — template engine

Documentation

If you want to… Read
Get started using the package Quick Start above
See practical, real-world usage docs/patterns.md
Understand the architecture and design decisions docs/design.md
Navigate and understand the source docs/source-guide.md
Run working examples examples/

Metadata

Release files for vcti-template 2.0.1

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for vcti-template 2.0.1
File Size Uploaded Provenance Actions
vcti_template-2.0.1.tar.gz 37.9 kB With provenance Details for vcti_template-2.0.1.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for vcti-template 2.0.1
File Interpreter ABI Platform Actions
vcti_template-2.0.1-py3-none-any.whl Python 3 none any Details for vcti_template-2.0.1-py3-none-any.whl

Total release size: 55.9 kB

Release files / vcti_template-2.0.1.tar.gz

Download URL vcti_template-2.0.1.tar.gz
Size 37.9 kB
Tags Source
SHA-256 checksum
How to use checksums
f2f96b240a0902f003c14e4046e09ed35313d100b80e1c412fc4d23a16d4a144
BLAKE2b-256 checksum
How to use checksums
316efb3522309ebbdb216a5c8e65af91f32d6efd062a456a49b00252d0b5afc4
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.14

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Sep 3, 2026.

Transparency log

Release files / vcti_template-2.0.1-py3-none-any.whl

Download URL vcti_template-2.0.1-py3-none-any.whl
Size 18.0 kB
Tags Python 3
SHA-256 checksum
How to use checksums
da19775e078cdd13a5830baf32b25d362b67913b57f7b9a50b09cbf32a9288b7
BLAKE2b-256 checksum
How to use checksums
1b9e6a42315d641ec6066f07b28e4743c826fc0d3a1071245c794cbda33c2755
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.14

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Sep 3, 2026.

Transparency log

Security for vcti-template 2.0.1

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for vcti_template-2.0.1.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Sep 3, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page