← flask-blog

jinja2 macros intro

f0b4c07bf777262e8e12f2b493cef8fa7df3f84a · ovidiucs · May 12, 2015 20:40

+24 −23 · 2 files changed

  • templates/macros.html +16 −0
  • templates/weather-average.html +8 −23
diff --git a/templates/macros.html b/templates/macros.html
new file mode 100644
index 0000000..23a6b98
--- /dev/null
+++ b/templates/macros.html
@@ -0,0 +1,16 @@
+{% macro weather_cell(value,hl) %}
+    <td>
+        {% if hl %}<b>{% endif %}
+            {{ value }}
+        {% if hl %}</b>{% endif %}
+    </td>
+{% endmacro %}
+
+{% macro weather_row(month, min, max, rain, hl_min, hl_max, hl_rain) %}
+    <tr>
+        <td>{{ month }}</td>
+        {{ weather_cell(min, min <= hl_min) }}
+        {{ weather_cell(max,max >= hl_max) }}
+        {{ weather_cell(rain,rain >= hl_rain) }}
+    </tr>
+{% endmacro %}
\ No newline at end of file
diff --git a/templates/weather-average.html b/templates/weather-average.html
index d9a6bff..88bb6a9 100644
--- a/templates/weather-average.html
+++ b/templates/weather-average.html
@@ -1,3 +1,4 @@
+{% import 'macros.html' as macros %}
 <h1>Weather Averages</h1>
 <h2>{{ city }}</h2>
 <hr>
@@ -9,28 +10,12 @@
         <th>Rainfall</th>
     </tr>
     {% for month in months %}
-        <tr>
-            <td>{{ month }}</td>
-            <td>
-                {% set hl = weather[month]['min'] <= highlight['min'] %}
-            {# set a variable hl, to a condition if, number to show is less
-            row equal to highlight minimum  #}
-                {% if hl %}<b>{% endif %}
-                {{ weather[month]['min'] }}
-                {% if hl %}</b>{% endif %}
-            </td>
-            <td>
-                {% set hl = weather[month]['max'] >= highlight['max'] %}
-                {% if hl %}<b>{% endif %}
-                {{ weather[month]['max'] }}
-                {% if hl %}</b>{% endif %}
-            </td>
-            <td>
-                {% set hl = weather[month]['rain'] >= highlight['rain'] %}
-                {% if hl %}<b>{% endif %}
-                {{ weather[month]['rain'] }}
-                {% if hl %}</b>{% endif %}
-            </td>
-        </tr>
+        {{ macros.weather_row(month,
+                weather[month]['min'],
+                weather[month]['max'],
+                weather[month]['rain'],
+                highlight['min'],
+                highlight['max'],
+                highlight['rain']) }}
     {% endfor %}
 </table>
\ No newline at end of file