Project 2: Habit Tracker: Adding date navigation (+41, -2)

app.py (+27, -2)

From: curriculum/section10/lectures/04_date_navigation/start/app.py

To: curriculum/section10/lectures/04_date_navigation/end/app.py

            
            index ae48b8f..20c4b6e 100644
--- a/curriculum/section10/lectures/04_date_navigation/start/app.py
+++ b/curriculum/section10/lectures/04_date_navigation/end/app.py
@@ -1,12 +1,33 @@
+import datetime
 from flask import Flask, render_template, request
 
 app = Flask(__name__)
 habits = ["Test habit"]
 
 
+@app.context_processor
+def add_calc_date_range():
+    def date_range(start: datetime.date):
+        dates = [start + datetime.timedelta(days=diff) for diff in range(-3, 4)]
+        return dates
+
+    return {"date_range": date_range}
+
+
 @app.route("/")
 def index():
-    return render_template("index.html", habits=habits, title="Habit Tracker - Home")
+    date_str = request.args.get("date")
+    if date_str:
+        selected_date = datetime.date.fromisoformat(date_str)
+    else:
+        selected_date = datetime.date.today()
+
+    return render_template(
+        "index.html",
+        habits=habits,
+        selected_date=selected_date,
+        title="Habit Tracker - Home",
+    )
 
 
 @app.route("/add", methods=["GET", "POST"])
@@ -14,4 +35,8 @@ def add_habit():
     if request.form:
         habits.append(request.form.get("habit"))
 
-    return render_template("add_habit.html", title="Habit Tracker - Add Habit")
+    return render_template(
+        "add_habit.html",
+        title="Habit Tracker - Add Habit",
+        selected_date=datetime.date.today(),
+    )
        

layout.html (+14, -0)

From: curriculum/section10/lectures/04_date_navigation/start/templates/layout.html

To: curriculum/section10/lectures/04_date_navigation/end/templates/layout.html

            
            index 08b597a..e2e0788 100644
--- a/curriculum/section10/lectures/04_date_navigation/start/templates/layout.html
+++ b/curriculum/section10/lectures/04_date_navigation/end/templates/layout.html
@@ -20,6 +20,20 @@
         </header>
 
         <main class="main">
+            <section class="dates">
+                {% for date in date_range(selected_date) %}
+                    <a 
+                        class="dates__link {{ 'dates__link--current' if loop.index0 == 3 else ''}}"
+                        href="{{ url_for('index', date=date) }}"
+                    >
+                        <time class="date" datetime="{{ date }}">
+                            <span>{{ date.strftime("%a") }}</span>
+                            <span>{{ date.strftime("%d") }}</span>
+                        </time>
+                    </a>
+                {% endfor %}
+            </section>
+
             {% block main_content %}
             {% endblock %}
         </main>