Closed
Description
Hey there,
First of all, thanks for putting this tutorial together - it's been really useful thus far! As I was going through this I caught a small bug in the following code in your navigation.html
file.
<header>
<nav>
{% for link in nav %}
<a href="{{link.url}}">{{link.name}}</a>
{% endfor %}
</nav>
</header>
Since we are passing in a List[Dict]
in routes.py
, in Python you cannot access dictionary keys with dot notation - it should instead be:
<header>
<nav>
{% for link in nav %}
<a href="{{link['url']}}">{{link['name']}}</a>
{% endfor %}
</nav>
</header>
While I agree with you that dot notation is a lot cleaner, we could alternatively define a Link
dataclass in routes.py
and instead of modifying navigation.html
, we could just edit routes.py
to have the following:
from dataclasses import dataclass
from flask import current_app as app
from flask import render_template
@dataclass
class Link:
url: str
name: str
@app.route('/')
def home():
"""Landing page"""
nav = [
Link(name="Home", url="https://example.com/1"),
Link(name="About", url="https://example.com/2"),
Link(name="Pics", url="https://example.com/3"),
]
return render_template(
'home.html.jinja',
title='Jinja Demo Site',
description='Flask & Jinja Tutorial',
nav=nav
)
Using this approach we could then safely use dot notation to access the name
and url
attributes for each Link
.
Let me know what you think.
Thanks!
Metadata
Metadata
Assignees
Labels
No labels