{% extends "base.html" %}
{% block title %}{% set this = section | default(value = page) %}{{ this.title }}{% endblock title %}
{% block head %}
{% endblock head %}
{% block content %}
{% set this = section | default(value = page) %}
{# Search this page-or-section's ancestor tree for a section that identifies itself as a book, and save it to a `book` variable #}
{% for ancestor_path in this.ancestors | concat(with = this.relative_path) %}
{# Get the ancestor section from this ancestor path string #}
{% if ancestor_path is ending_with("/_index.md") %}
{% set potential_book = get_section(path = ancestor_path) %}
{% endif %}
{# Check if the ancestor section is the root of a book, and if so, set it to a variable accessible outside the loop #}
{% if potential_book.extra.book %}
{% set_global book = get_section(path = potential_book.path ~ "_index.md" | trim_start_matches(pat="/")) %}
{% endif %}
{% endfor %}
{# Map this book's chapter path strings to an array of sections #}
{% set chapters = [] %}
{% for chapter_path in book.subsections %}
{% set_global chapters = chapters | concat(with = get_section(path = chapter_path)) %}
{% endfor %}
{% set chapters = chapters | sort(attribute = "extra.order") %}
{# A flat list of all pages in the ToC, initialized to just the book root section but updated when we generate the ToC #}
{% set flat_pages = [book] %}
{% set flat_index_of_this = 0 %}
{{ this.title }}
{{ this.content | safe }}
{% if flat_index_of_this >= 1 %}
{% set prev = flat_pages | nth(n = flat_index_of_this - 1) %}
{% endif %}
{% if prev %}
{{ prev.title }}
{% else %}
{% endif %}
{% if flat_index_of_this < flat_pages | length - 1 %}
{% set next = flat_pages | nth(n = flat_index_of_this + 1) %}
{% endif %}
{% if next %}
{{ next.title }}
{% endif %}