{% macro Page(pagination, route, i, label=None, disabled=False, portfolio_id=None) -%}
  {% set label = label or i %}

  {% set button_class = "page usa-button " %}

  {% if disabled %}
    {% set button_class = button_class + "usa-button-disabled" %}
  {% elif i == pagination.page %}
    {% set button_class = button_class + "usa-button-primary" %}
  {% else %}
    {% set button_class = button_class + "usa-button-secondary" %}
  {% endif %}

    <a id="{{ label }}" type="button" class="{{ button_class }}" href="{{ url_for(route, portfolio_id=portfolio_id, page=i, perPage=pagination.per_page) if not disabled else 'null' }}">{{ label }}</a>
{%- endmacro %}

{% macro Pagination(pagination, route, portfolio_id=None) -%}
  <div class="pagination">

    {% if pagination.page == 1 %}
      {{ Page(pagination, route, 1, label="first", disabled=True, portfolio_id=portfolio_id) }}
      {{ Page(pagination, route, pagination.page - 1, label="prev", disabled=True, portfolio_id=portfolio_id) }}
    {% else %}
      {{ Page(pagination, route, 1, label="first", portfolio_id=portfolio_id) }}
      {{ Page(pagination, route, pagination.page - 1, label="prev", portfolio_id=portfolio_id) }}
    {% endif %}

    {% if pagination.page == 1 %}
      {% set max_page = [pagination.pages, 5] | min %}
      {% for i in range(1, max_page + 1) %}
        {{ Page(pagination, route, i, portfolio_id=portfolio_id) }}
      {% endfor %}
    {% elif pagination.page == pagination.pages %}
      {% for i in range(pagination.pages - 4, pagination.pages + 1) %}
        {% if i > 0 %}
          {{ Page(pagination, route, i, portfolio_id=portfolio_id) }}
        {% endif %}
      {% endfor %}
    {% else %}
      {% set window = pagination | pageWindow %}
      {% for i in range(window.0, window.1 + 1) %}
        {{ Page(pagination, route, i, portfolio_id=portfolio_id) }}
      {% endfor %}
    {% endif %}

    {% if pagination.page == pagination.pages %}
      {{ Page(pagination, route, pagination.page + 1, label="next", disabled=True, portfolio_id=portfolio_id) }}
      {{ Page(pagination, route, pagination.pages, label="last", disabled=True, portfolio_id=portfolio_id) }}
    {% else %}
      {{ Page(pagination, route, pagination.page + 1, label="next", portfolio_id=portfolio_id) }}
      {{ Page(pagination, route, pagination.pages, label="last", portfolio_id=portfolio_id) }}
    {% endif %}

  </div>
{%- endmacro %}
