| 1 |
from pathlib import Path |
| 2 |
|
| 3 |
from litestar import Litestar, get |
| 4 |
from litestar.contrib.minijinja import MiniJinjaTemplateEngine, StateProtocol |
| 5 |
from litestar.response import Template |
| 6 |
from litestar.template.config import TemplateConfig |
| 7 |
|
| 8 |
|
| 9 |
def my_template_function(ctx: StateProtocol) -> str: |
| 10 |
return ctx.lookup("my_context_key") or "nope" |
| 11 |
|
| 12 |
|
| 13 |
def register_template_callables(engine: MiniJinjaTemplateEngine) -> None: |
| 14 |
engine.register_template_callable(key="check_context_key", template_callable=my_template_function) |
| 15 |
|
| 16 |
|
| 17 |
template_config = TemplateConfig( |
| 18 |
directory=Path(__file__).parent / "templates", |
| 19 |
engine=MiniJinjaTemplateEngine, |
| 20 |
engine_callback=register_template_callables, |
| 21 |
) |
| 22 |
|
| 23 |
|
| 24 |
@get("/", sync_to_thread=False) |
| 25 |
def index() -> Template: |
| 26 |
return Template(template_name="index.html.minijinja") |
| 27 |
|
| 28 |
|
| 29 |
app = Litestar(route_handlers=[index], template_config=template_config) |