File: template_functions_mako.py

package info (click to toggle)
litestar 2.21.0-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 12,568 kB
  • sloc: python: 70,588; makefile: 254; javascript: 104; sh: 60
file content (36 lines) | stat: -rw-r--r-- 898 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
from pathlib import Path
from typing import Any, Dict

from litestar import Litestar, get
from litestar.contrib.mako import MakoTemplateEngine
from litestar.response import Template
from litestar.template.config import TemplateConfig


def my_template_function(ctx: Dict[str, Any]) -> str:
    return ctx.get("my_context_key", "nope")


def register_template_callables(engine: MakoTemplateEngine) -> None:
    engine.register_template_callable(
        key="check_context_key",
        template_callable=my_template_function,
    )


template_config = TemplateConfig(
    directory=Path(__file__).parent / "templates",
    engine=MakoTemplateEngine,
    engine_callback=register_template_callables,
)


@get("/", sync_to_thread=False)
def index() -> Template:
    return Template(template_name="index.html.mako")


app = Litestar(
    route_handlers=[index],
    template_config=template_config,
)