Skip to content

Commit

Permalink
Refactor a bit
Browse files Browse the repository at this point in the history
  • Loading branch information
Kludex committed May 31, 2023
1 parent 98d0c60 commit a46a825
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 34 deletions.
14 changes: 11 additions & 3 deletions docs/templates.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,14 @@
Starlette is not _strictly_ coupled to any particular templating engine, but
Jinja2 provides an excellent choice.

### Jinja2Templates

Signature: `Jinja2Templates(directory, context_processors=None, **env_options)`

* `directory` - A string, [os.Pathlike][pathlike] or a list of strings or [os.Pathlike][pathlike] denoting a directory path.
* `context_processors` - A list of functions that return a dictionary to add to the template context.
* `**env_options` - Additional keyword arguments to pass to the Jinja2 environment.

Starlette provides a simple way to get `jinja2` configured. This is probably
what you want to use by default.

Expand All @@ -24,9 +32,8 @@ routes = [
app = Starlette(debug=True, routes=routes)
```

Note that:

* The incoming `request` instance must be included as part of the template context.
Note that the incoming `request` instance must be included as part of the
template context.

* `directory=` can accept a sequence, e.g. `Jinja2Templates(directory=['templates', 'more_templates'])`.

Expand Down Expand Up @@ -131,3 +138,4 @@ for example, strictly evaluate any database queries within the view and
include the final results in the context.

[jinja2]: https://jinja.palletsprojects.com/en/3.0.x/api/?highlight=environment#writing-filters
[pathlike]: https://docs.python.org/3/library/os.html#os.PathLike
54 changes: 23 additions & 31 deletions tests/test_templates.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ def test_template_response_requires_request(tmpdir):


def test_calls_context_processors(tmp_path, test_client_factory):
path: Path = tmp_path / "index.html"
path = tmp_path / "index.html"
path.write_text("<html>Hello {{ username }}</html>")

async def homepage(request):
Expand Down Expand Up @@ -91,44 +91,36 @@ async def dispatch(self, request, call_next):
assert set(response.context.keys()) == {"request"}


def test_templates_with_directories(tmp_path, test_client_factory):
dir_home: Path = tmp_path.resolve() / "home"
dir_home.mkdir()
template = dir_home / "index.html"
with template.open("w") as file:
file.write("<html>Hello, <a href='{{ url_for('homepage') }}'>world</a></html>")
def test_templates_with_directories(tmp_path: Path, test_client_factory):
dir_a = tmp_path.resolve() / "a"
dir_a.mkdir()
template_a = dir_a / "template_a.html"
template_a.write_text("<html>Hello, <a href='{{ url_for('page_a') }}'></a> a</html>")

async def homepage(request):
return templates.TemplateResponse("index.html", {"request": request})
async def page_a(request):
return templates.TemplateResponse("template_a.html", {"request": request})

dir_A: Path = dir_home.parent.resolve() / "A"
dir_A.mkdir()
template_A = dir_A / "template_A.html"
with template_A.open("w") as file:
file.write("<html>Hello, <a href='{{ url_for('get_A') }}'></a> A</html>")
dir_b = tmp_path.resolve() / "b"
dir_b.mkdir()
template_b = dir_a / "template_b.html"
template_b.write_text("<html>Hello, <a href='{{ url_for('page_b') }}'></a> b</html>")

async def get_A(request):
return templates.TemplateResponse("template_A.html", {"request": request})
async def page_b(request):
return templates.TemplateResponse("template_b.html", {"request": request})

app = Starlette(
debug=True,
routes=[Route("/", endpoint=homepage), Route("/A", endpoint=get_A)],
routes=[Route("/a", endpoint=page_a), Route("/b", endpoint=page_b)],
)
templates = Jinja2Templates(directory=[dir_home, dir_A])

assert dir_home != dir_A
with pytest.raises(ValueError):
dir_home.relative_to(dir_A)
with pytest.raises(ValueError):
assert not dir_A.relative_to(dir_home)
templates = Jinja2Templates(directory=[dir_a, dir_b])

client = test_client_factory(app)
response = client.get("/")
assert response.text == "<html>Hello, <a href='http://testserver/'>world</a></html>"
assert response.template.name == "index.html"
response = client.get("/a")
assert response.text == "<html>Hello, <a href='http://testserver/a'></a> a</html>"
assert response.template.name == "template_a.html"
assert set(response.context.keys()) == {"request"}

response_A = client.get("/A")
assert response_A.text == "<html>Hello, <a href='http://testserver/A'></a> A</html>"
assert response_A.template.name == "template_A.html"
assert set(response_A.context.keys()) == {"request"}
response = client.get("/b")
assert response.text == "<html>Hello, <a href='http://testserver/b'></a> b</html>"
assert response.template.name == "template_b.html"
assert set(response.context.keys()) == {"request"}

0 comments on commit a46a825

Please sign in to comment.