Loading Templates
You can load templates from a file system or database, for example, by creating an Environment
and configuring a template loader. You'd also need a loader if you want to use the built-in {% include %}
or {% render %}
tags.
Environment.get_template()
and Environment.get_template_async()
accept a template name and return a BoundTemplate
. That is a template bound to the environment, ready to be rendered. It is up to the loader to interpret a template name. In the case of FileSystemLoader
, the name would be a file name, possibly preceded by a path relative to the configured search path.
Built-in loaders include CachingFileSystemLoader
, FileSystemLoader
, FileExtensionLoader
, DictLoader
, ChoiceLoader
and CachingChoiceLoader
. See also custom loaders, and examples of a FrontMatterFileSystemLoader
and an AsyncDatabaseLoader
.
This FileSystemLoader
example assumes a folder called templates
exists in the current working directory, and that template files index.html
and some-list.html
exist within it.
<!doctype html>
<html lang="en">
<head>
<title>{{ page_title }}</title>
</head>
<body>
<h1>{{ heading }}</h1>
{% render 'some-list.html' with people %}
</body>
</html>
<ul>
{% for person in people %}
<li>{{ person.name }}</li>
{% endfor %}
</ul>
By default, every Environment
is created with an empty DictLoader
. Specify an alternative template loader using the loader
argument.
from liquid import Environment
from liquid import FileSystemLoader
env = Environment(loader=FileSystemLoader("templates/"))
people = [
{"name": "John"},
{"name": "Sally"},
]
template = env.get_template("index.html")
print(template.render(
heading="Some List",
page_title="Awesome Title",
people=people,
))
<!doctype html>
<html lang="en">
<head>
<title>Awesome Title</title>
</head>
<body>
<h1>Some List</h1>
<ul>
<li>John</li>
<li>Sally</li>
</ul>
</body>
</html>
Notice how whitespace is output unchanged. See whitespace control
for more information.
Caching File System Loader
New in version 1.9.0
When rendering partial templates with {% include %}
or {% render %}
, or making use of Python Liquid's template inheritance features, it is recommended to use a caching loader such as CachingFileSystemLoader
or CachingChoiceLoader
or a custom loader that handles its own cache.
from liquid import CachingFileSystemLoader
from liquid import Environment
loader = CachingFileSystemLoader("templates/", cache_size=500)
env = Environment(loader=loader)
# ...