Jinja2 Mastery: Level 1: Simplifying your Jinja code with macros (+36, -1)
app.py (+5, -1)
From:
curriculum/section09/lectures/04_jinja2_macros/start/app.py
To:
curriculum/section09/lectures/04_jinja2_macros/end/app.py
index 25bacfd..6f202a3 100644
--- a/curriculum/section09/lectures/04_jinja2_macros/start/app.py
+++ b/curriculum/section09/lectures/04_jinja2_macros/end/app.py
@@ -3,7 +3,11 @@ from flask import Flask, render_template
app = Flask(__name__)
+todos = [
+ ("Get milk", False),
+ ("Learn programming", True)
+]
@app.route("/")
def todo():
- return render_template("home.html", todos=["Get milk", "Learn programming"])
+ return render_template("home.html", todos=todos)
home.html (+20, -0)
From:
curriculum/section09/lectures/04_jinja2_macros/start/templates/home.html
To:
curriculum/section09/lectures/04_jinja2_macros/end/templates/home.html
index d58fdf4..7e981cf 100644
--- a/curriculum/section09/lectures/04_jinja2_macros/start/templates/home.html
+++ b/curriculum/section09/lectures/04_jinja2_macros/end/templates/home.html
@@ -1,3 +1,13 @@
+<!-- step 1-->
+{% macro todo_li(text, completed=False) %}
+ <li>{{ "[x]" if completed else "[ ]" }} - {{ text }}</li>
+{% endmacro %}
+
+<!-- step 2 -->
+{% import 'macros.html' as macros %}
+<!-- or -->
+{% from 'macros.html' import todo_list %}
+
<!DOCTYPE html>
<html lang="en">
<head>
@@ -9,6 +19,16 @@
{% set num_todos = todos | length %}
{% if num_todos > 0 %}
<p>You have {{ num_todos }} things to do today.</p>
+ <!-- step 1 -->
+ <ul>
+ {% for text, completed in todos %}
+ {{ todo_li(text, completed) }}
+ {% endfor %}
+ </ul>
+ <!-- step 2 -->
+ {{ macros.todo_list(todos) }}
+ <!-- or -->
+ {{ todo_list(todos) }}
{% else %}
<p>Nothing to do today. Relax!</p>
{% endif %}
macros.html (+11, -0)
From:
curriculum/section09/lectures/04_jinja2_macros/end/templates/macros.html
To:
curriculum/section09/lectures/04_jinja2_macros/end/templates/macros.html
new file mode 100644
index 0000000..4340254
--- /dev/null
+++ b/curriculum/section09/lectures/04_jinja2_macros/end/templates/macros.html
@@ -0,0 +1,11 @@
+{% macro todo_li(text, completed=False) %}
+ <li>{{ "[x]" if completed else "[ ]" }} - {{ text }}</li>
+{% endmacro %}
+
+{% macro todo_list(todos) %}
+ <ul>
+ {% for text, completed in todos %}
+ {{ todo_li(text, completed) }}
+ {% endfor %}
+ </ul>
+{% endmacro %}