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