Jinja¶
Provides support for Jinja templates.
Usage¶
First install the jinja extra:
$ pip install zayt-contrib[jinja]
Activate the module in the configuration file:
settings.toml¶
modules = [
"zayt_contrib.jinja",
]
Inject the JinjaTemplate service and call
the respond() method:
application.py¶
from zayt_contrib.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 settings.toml and by providing services.
For example, to activate Jinja extensions:
settings.toml¶
modules = ["zayt_contrib.jinja"]
[jinja]
extensions = [
"jinja2.ext.i18n",
"jinja2.ext.debug",
]
Services¶
The extension will look for the following services:
jinja2.BaseLoaderjinja2.BytecodeCache
Example:
from zayt import di
from jinja2 import BaseLoader, DictLoader, FileSystemBytecodeCache
@di.service
def jinja_loader() -> BaseLoader:
return DictLoader({'index.html': '...'})
@di.service
def bytecode_cache() -> BytecodeCache:
return FileSystemBytecodeCache('/tmp/jinja_cache', '%s.cache')
Configuration options¶
[jinja]
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 = "path.to.Class"
finalize = "path.to.function"
autoescape = "path.to.function"
cache_size = 1
auto_reload = true
[jinja.loader]
searchpath = ["resources/templates"]
encoding = "utf-8"
followlinks = false
Note
The options are described in jinja2.Environment.