Jinja¶
Provides support for Jinja templates.
Usage¶
First install the jinja extra:
$ pip install zayt[jinja]
Activate the module in the configuration file:
settings.py¶
settings = {
"modules": [
"zayt.ext.jinja",
],
}
Inject the JinjaTemplate service and call
the respond() method:
application.py¶
from zayt.ext.jinja import JinjaTemplate
from zayt.web import get
@get
async def index(request, template: JinjaTemplate):
context = {"title": "Index"}
await template.respond(request, "index.html", context)
resources/templates/index.html¶
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Jinja Templates</title>
</head>
<body>
<h1>{{ title }}</h1>
</body>
</html>
Render templates to string¶
The JinjaTemplate class provide methods to render templates
into a str, instead of rendering to the response.
The method render() accepts a template name
and returns a string with the rendered template.
The method render_str() accepts a template
string, compiles it and returns the result.
template.render("template.html", {"variable": "value"})
template.render_str("{{ variable }}", {"variable": "value"})
Configuration¶
Jinja can be configured through the settings.py. For example, to activate Jinja extensions:
settings.py¶
settings = {
"extensions": ["zayt.ext.jinja"],
"jinja": {
"entensions": [
"jinja2.ext.i18n",
"jinja2.ext.debug",
],
},
}
The available options are shown below:
settings = {
"jinja": {
"loader: {
"searchpath": [
"resources/templates"
],
"encoding": "utf-8",
"followlinks": False,
},
# "loader": loader_instance,
"block_start_string": "",
"block_end_string": "",
"variable_start_string": "",
"variable_end_string": "",
"comment_start_string": "",
"comment_end_string": "",
"line_statement_prefix": "",
"line_comment_prefix": "",
"trim_blocks": True,
"lstrip_blocks": True,
"newline_sequence": "\n", # "\r\n", "\r"
"keep_trailing_newline": True,
"extensions": [
"extension1",
"extension2",
],
"optimized": True,
"undefined": SomeClass,
"finalize": some_function,
"autoescape": some_function,
"cache_size": 1,
"auto_reload": True,
"bytecode_cache": cache_instance
},
}
Note
The options are described in jinja2.Environment.
Note
The loader option can be a jinja2.BaseLoader instance or a dict.