# Simplifying your Jinja code with macros

# In this video... (TL;DR)

TIP

List of all code changes made in this lecture: https://diff-store.com/diff/section09__04_jinja2_macros (opens new window)

Another thing in Jinja similar to functions in Python, but here they're used for composition rather than transformation.

The process for using macros starts by extraction: extract some existing Jinja code into a macro so that you can call it from anywhere, and reuse it in multiple places.

{% macro alert(title, message) %}
	<div class="alert alert-warning">
		<p class="alert__title">{{ title }}</p>
		<p class="alert__body">{{ message }}</p>
	</div>
{% endmacro %}

# Code at the start of this lecture

{% set num_todos = todos | length %}
  {% if num_todos > 0 %}
      <p>You have {{ num_todos }} things to do today.</p>
      <ul>
        {% for text, completed in todos %}
          <li>{{ "[x]" if completed else "[ ]" }} - {{ text }}</li>
        {% endfor %}
      </ul>
  {% else %}
      <p>Nothing to do today. Relax!</p>
  {% endif %}

# Code written in this lecture

# Step 1

{% macro todo_li(text, completed=False) %}
  <li>{{ "[x]" if completed else "[ ]" }} - {{ text }}</li>
{% endmacro %}

{% set num_todos = todos | length %}
  {% if num_todos > 0 %}
      <p>You have {{ num_todos }} things to do today.</p>
      <ul>
        {% for text, completed in todos %}
          {{ todo_li(text, completed) }}
        {% endfor %}
      </ul>
  {% else %}
      <p>Nothing to do today. Relax!</p>
  {% endif %}

# Step 2

{% import 'macros.html' as macros %}
<!-- or -->
{% from 'macros.html' import todo_list %}

{% set num_todos = todos | length %}
  {% if num_todos > 0 %}
      <p>You have {{ num_todos }} things to do today.</p>

      {{ macros.todo_list(todos) }}
      <!-- or -->
      {{ todo_list(todos) }}
  {% else %}
      <p>Nothing to do today. Relax!</p>
  {% endif %}

# Final code at the end of this lecture

{% import 'macros.html' as macros %}

{% set num_todos = todos | length %}
  {% if num_todos > 0 %}
      <p>You have {{ num_todos }} things to do today.</p>

      {{ macros.todo_list(todos) }}
  {% else %}
      <p>Nothing to do today. Relax!</p>
  {% endif %}