Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow env_options in `Jinja2Templates #1401

Merged
merged 6 commits into from Jan 19, 2022
Merged
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
13 changes: 9 additions & 4 deletions starlette/templating.py
Expand Up @@ -55,20 +55,25 @@ class Jinja2Templates:
return templates.TemplateResponse("index.html", {"request": request})
"""

def __init__(self, directory: typing.Union[str, PathLike]) -> None:
def __init__(
self, directory: typing.Union[str, PathLike], **env_options: typing.Any
) -> None:
assert jinja2 is not None, "jinja2 must be installed to use Jinja2Templates"
self.env = self._create_env(directory)
self.env = self._create_env(directory, **env_options)

def _create_env(
self, directory: typing.Union[str, PathLike]
self, directory: typing.Union[str, PathLike], **env_options: typing.Any
) -> "jinja2.Environment":
@pass_context
def url_for(context: dict, name: str, **path_params: typing.Any) -> str:
request = context["request"]
return request.url_for(name, **path_params)

loader = jinja2.FileSystemLoader(directory)
env = jinja2.Environment(loader=loader, autoescape=True)
env_options.setdefault("loader", loader)
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We can decide if we want to allow loader to be passed in env_options or not. The point is if we add it it makes directory reduntant but allows user full control over the loader.

env_options.setdefault("autoescape", True)

env = jinja2.Environment(**env_options)
env.globals["url_for"] = url_for
return env

Expand Down