Skip to content

Commit

Permalink
馃摑 Update template docs with more info about url_for (#5937)
Browse files Browse the repository at this point in the history
Co-authored-by: Sebasti谩n Ram铆rez <tiangolo@gmail.com>
  • Loading branch information
EzzEddin and tiangolo committed Jan 11, 2024
1 parent 22e68b1 commit 0c79674
Show file tree
Hide file tree
Showing 3 changed files with 49 additions and 6 deletions.
48 changes: 44 additions & 4 deletions docs/en/docs/advanced/templates.md
Expand Up @@ -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
<a href="{{ url_for('read_item', id=id) }}">
```

{% 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
<a href="/items/42">
```

## 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!}
Expand Down
2 changes: 1 addition & 1 deletion docs_src/templates/templates/item.html
Expand Up @@ -4,6 +4,6 @@
<link href="{{ url_for('static', path='/styles.css') }}" rel="stylesheet">
</head>
<body>
<h1>Item ID: {{ id }}</h1>
<h1><a href="{{ url_for('read_item', id=id) }}">Item ID: {{ id }}</a></h1>
</body>
</html>
5 changes: 4 additions & 1 deletion tests/test_tutorial/test_templates/test_tutorial001.py
Expand Up @@ -16,7 +16,10 @@ def test_main():
client = TestClient(app)
response = client.get("/items/foo")
assert response.status_code == 200, response.text
assert b"<h1>Item ID: foo</h1>" in response.content
assert (
b'<h1><a href="http://testserver/items/foo">Item ID: foo</a></h1>'
in response.content
)
response = client.get("/static/styles.css")
assert response.status_code == 200, response.text
assert b"color: green;" in response.content
Expand Down

0 comments on commit 0c79674

Please sign in to comment.