Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
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
14 changes: 14 additions & 0 deletions docs/templates.md
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,20 @@ def test_homepage():
assert "request" in response.context
```

## Customizing Jinja2 Environment

`Jinja2Templates` accepts all options supported by Jinja2 `Environment`.
This will allow more control over the `Enivornment` instance created by Starlette.

For the list of options available to `Environment` you can check Jinja2 documentation [here](https://jinja.palletsprojects.com/en/3.0.x/api/#jinja2.Environment)

```python
from starlette.templating import Jinja2Templates


templates = Jinja2Templates(directory='templates', autoescape=False, auto_reload=True)
```

## Asynchronous template rendering

Jinja2 supports async template rendering, however as a general rule
Expand Down
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
Copy Markdown
Contributor 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