Skip to content

Rendering templates

As simple as possible

For one-off templates using nothing but the default tags and filters, and without the possibility of including, rendering or extending other templates, use the package-level render() function.

It takes template source text as a string and any number of keyword arguments that will be made available as template variables, returning a string.

from liquid2 import render

result = render("Hello, {{ you }}!", you="World")

If you want to render the same template multiple times with different data, use the package-level parse() function. It takes template source text as a string, an optional name for the template and an optional dictionary of variables to attach to the template. An instance of Template with a render() method is returned.

from liquid2 import parse

template = parse("Hello, {{ you }}!")
result = template.render(you="World")
another_result = template.render(you="Liquid")

Common configuration

Often, at a minimum, you'll want to configure a template loader that reads template source text from a file system. Doing this will tell the template engine where to look for templates when including, rendering or extending other templates.

from liquid2 import Environment
from liquid2 import CachingFileSystemLoader

env = Environment(
    loader=CachingFileSystemLoader("path/to/templates", ext=".html"),
)

Now, if there's a file called "main.html" in "/path/to/templates/", we can use env.get_template() to load and parse it, along with any templates it includes, renders or extends.

# ... continued from above
template = env.get_template("main.html")
data = {"foo": 42, "bar": "hello"}
result = render(**data)

See Liquid environments for more information about configuring an Environment and loading templates for details of the built-in template loaders.