Jinja¶
Provê suporte para templates Jinja
Utilização¶
Primeiro instale o extra jinja:
$ pip install zayt-contrib[jinja]
Ative o módulo no arquivo de configuração:
settings.toml¶
modules = [
"zayt_contrib.jinja",
]
Injeto o serviço JinjaTemplate e invoque o método respond():
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>
Renderizar templates para string¶
A classe JinjaTemplate provê métodos para renderizar templates para um str ao invés de renderizar para a resposta.
O método render() aceita um nome de template e retorna uma string com o template renderizado.
O método render_str() aceita uma string de template, a compila e retorna o resultado.
template.render("template.html", {"variable": "value"})
template.render_str("{{ variable }}", {"variable": "value"})
Configuração¶
Jinja pode ser configurado através do settings.toml. Por exemplo, para ativar extensões do Jinja:
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')
Opções de configuração¶
[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
Nota
As opções são descritas em jinja2.Environment.