diff --git a/docs/en/docs/advanced/templates.md b/docs/en/docs/advanced/templates.md index 583abda7fb0e4..6055b30170db6 100644 --- a/docs/en/docs/advanced/templates.md +++ b/docs/en/docs/advanced/templates.md @@ -46,21 +46,61 @@ $ pip install jinja2 ## Writing templates -Then you can write a template at `templates/item.html` with: +Then you can write a template at `templates/item.html` with, for example: ```jinja hl_lines="7" {!../../../docs_src/templates/templates/item.html!} ``` -It will show the `id` taken from the "context" `dict` you passed: +### Template Context Values + +In the HTML that contains: + +{% raw %} + +```jinja +Item ID: {{ id }} +``` + +{% endraw %} + +...it will show the `id` taken from the "context" `dict` you passed: ```Python -{"request": request, "id": id} +{"id": id} +``` + +For example, with an ID of `42`, this would render: + +```html +Item ID: 42 +``` + +### Template `url_for` Arguments + +You can also use `url_for()` inside of the template, it takes as arguments the same arguments that would be used by your *path operation function*. + +So, the section with: + +{% raw %} + +```jinja + +``` + +{% endraw %} + +...will generate a link to the same URL that would be handled by the *path operation function* `read_item(id=id)`. + +For example, with an ID of `42`, this would render: + +```html + ``` ## Templates and static files -You can also use `url_for()` inside of the template, and use it, for example, with the `StaticFiles` you mounted. +You can also use `url_for()` inside of the template, and use it, for example, with the `StaticFiles` you mounted with the `name="static"`. ```jinja hl_lines="4" {!../../../docs_src/templates/templates/item.html!} diff --git a/docs_src/templates/templates/item.html b/docs_src/templates/templates/item.html index a70287e77d345..27994ca994b00 100644 --- a/docs_src/templates/templates/item.html +++ b/docs_src/templates/templates/item.html @@ -4,6 +4,6 @@ -

Item ID: {{ id }}

+

Item ID: {{ id }}

diff --git a/tests/test_tutorial/test_templates/test_tutorial001.py b/tests/test_tutorial/test_templates/test_tutorial001.py index bfee5c0902dbc..4d4729425e845 100644 --- a/tests/test_tutorial/test_templates/test_tutorial001.py +++ b/tests/test_tutorial/test_templates/test_tutorial001.py @@ -16,7 +16,10 @@ def test_main(): client = TestClient(app) response = client.get("/items/foo") assert response.status_code == 200, response.text - assert b"

Item ID: foo

" in response.content + assert ( + b'

Item ID: foo

' + in response.content + ) response = client.get("/static/styles.css") assert response.status_code == 200, response.text assert b"color: green;" in response.content