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
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 9 additions & 4 deletions starlette/templating.py
Original file line number Diff line number Diff line change
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
9 changes: 9 additions & 0 deletions tests/test_templates.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,3 +29,12 @@ def test_template_response_requires_request(tmpdir):
templates = Jinja2Templates(str(tmpdir))
with pytest.raises(ValueError):
templates.TemplateResponse(None, {})


def test_template_jinja2_env_options(tmpdir):
templates = Jinja2Templates(
directory=str(tmpdir), autoescape=False, auto_reload=True
)

assert templates.env.autoescape is False
assert templates.env.auto_reload is True