Skip to content

Commit fb19cf1

Browse files
euri10cofin
authored andcommitted
fix: template callable is now correctly registered in case a custom env is passed
1 parent 21efdbb commit fb19cf1

File tree

2 files changed

+40
-2
lines changed

2 files changed

+40
-2
lines changed

litestar/template/config.py

+5-1
Original file line numberDiff line numberDiff line change
@@ -54,4 +54,8 @@ def to_engine(self) -> EngineType:
5454
@cached_property
5555
def engine_instance(self) -> EngineType:
5656
"""Return the template engine instance."""
57-
return self.to_engine() if self.instance is None else self.instance
57+
if self.instance is None:
58+
return self.to_engine()
59+
if callable(self.engine_callback):
60+
self.engine_callback(self.instance)
61+
return self.instance

tests/unit/test_template/test_template.py

+35-1
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,10 @@
22

33
import sys
44
from pathlib import Path
5-
from typing import TYPE_CHECKING
5+
from typing import TYPE_CHECKING, Any
66

77
import pytest
8+
from jinja2 import DictLoader, Environment
89

910
from litestar import Litestar, MediaType, get
1011
from litestar.contrib.jinja import JinjaTemplateEngine
@@ -52,6 +53,39 @@ def callback(engine: TemplateEngineProtocol) -> None:
5253
assert received_engine is app.template_engine
5354

5455

56+
def test_engine_passed_to_callback_custom_env(tmp_path: Path) -> None:
57+
received_engine: JinjaTemplateEngine | None = None
58+
59+
def callback(engine: TemplateEngineProtocol) -> None:
60+
nonlocal received_engine
61+
assert isinstance(engine, JinjaTemplateEngine), "Engine must be a JinjaTemplateEngine"
62+
received_engine = engine
63+
engine.register_template_callable(
64+
key="check_context_key",
65+
template_callable=my_template_function,
66+
)
67+
68+
def my_template_function(ctx: dict[str, Any]) -> str:
69+
return ctx.get("my_context_key", "nope")
70+
71+
my_custom_env = Environment(loader=DictLoader({"index.html": "check_context_key: {{ check_context_key() }}"}))
72+
template_config = TemplateConfig(
73+
instance=JinjaTemplateEngine.from_environment(my_custom_env),
74+
engine_callback=callback,
75+
)
76+
app = Litestar(template_config=template_config)
77+
78+
@get("/")
79+
def handler() -> Template:
80+
return Template(template_name="index.html")
81+
82+
assert received_engine is not None
83+
assert received_engine is app.template_engine
84+
with create_test_client(route_handlers=[handler], template_config=template_config) as client:
85+
response = client.get("/")
86+
assert response.text == "check_context_key: nope"
87+
88+
5589
@pytest.mark.parametrize("engine", (JinjaTemplateEngine, MakoTemplateEngine, MiniJinjaTemplateEngine))
5690
def test_engine_instance(engine: type[TemplateEngineProtocol], tmp_path: Path) -> None:
5791
engine_instance = engine(directory=tmp_path, engine_instance=None)

0 commit comments

Comments
 (0)