Plain is headed towards 1.0! Subscribe for development updates →

Templates

Render HTML templates using Jinja.

Templates are typically rendered in TemplateViews, but you can also render them directly to strings for emails or other use cases.

from plain.templates import Template


Template("comment.md").render({
    "message": "Hello, world!",
})

Template files can be located in either a root app/templates, or the templates directory in any installed packages.

Customizing Jinja

 1import jinja2
 2
 3from .jinja import environment
 4
 5
 6class TemplateFileMissing(Exception):
 7    def __str__(self) -> str:
 8        if self.args:
 9            return f"Template file {self.args[0]} not found"
10        else:
11            return "Template file not found"
12
13
14class Template:
15    def __init__(self, filename: str) -> None:
16        self.filename = filename
17
18        try:
19            self._jinja_template = environment.get_template(filename)
20        except jinja2.TemplateNotFound:
21            raise TemplateFileMissing(filename)
22
23    def render(self, context: dict) -> str:
24        return self._jinja_template.render(context)