It would be nice to have a nice abstraction for injecting globals into templates so that we don't have to do such a dance around this current process (see #basic-examples)
Some examples of what is currently required I think:
@Alc-Alc's
"""Template config."""
from __future__ import annotations
import os
from typing import Any
from jinja2 import Environment
from litestar import Litestar
from litestar.contrib.jinja import JinjaTemplateEngine
from litestar.template.config import TemplateConfig
def create_environment() -> Environment:
env = Environment()
env.globals['BASE_PATH'] = "/prod-path" if os.getenv("ENVIRONMENT", "dev") == "prod" else "/"
return env
config = TemplateConfig(
directory="/path/to/templates",
engine=JinjaTemplateEngine.from_environment(create_environment()),
)
app = Litestar(template_config=config)
or mine
"""Template config."""
from __future__ import annotations
import os
from typing import Any
from jinja2 import Environment
from litestar import Litestar
from litestar.contrib.jinja import JinjaTemplateEngine
from litestar.template.config import TemplateConfig
def set_base_path(engine_instance: Any) -> None:
"""Set the base path for the template engine."""
env = os.getenv("ENVIRONMENT", "dev")
if hasattr(engine_instance, "engine") and isinstance(engine_instance.engine, Environment):
engine_instance.engine.globals["BASE_PATH"] = "/prod-path" if env == "prod" else "/"
config = TemplateConfig(
directory="/path/to/templates",
engine=JinjaTemplateEngine,
engine_callback=set_base_path,
)
app = Litestar(
template_config=config,
)
...and then:
<a href="{{ BASE_PATH }}">some link</a>
No response
Pay now to fund the work behind this issue.
Get updates on progress being made.
Maintainer is rewarded once the issue is completed.
You're funding impactful open source efforts
You want to contribute to this effort
You want to get funding like this too