Skip to content

Instantly share code, notes, and snippets.

@VincentLoy
Last active April 18, 2024 19:56
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save VincentLoy/e693aa1f149a59f465a5a71b6d937b9a to your computer and use it in GitHub Desktop.
Save VincentLoy/e693aa1f149a59f465a5a71b6d937b9a to your computer and use it in GitHub Desktop.
Easy snippet to get breadcrumb in a Wagtail page
<div class="breadcrumb-content">
{% if self.get_ancestors|length > 1 %}
<ul class="breadcrumb">
{% for p in self.get_ancestors %}
{% if p.is_root == False %}
<li><a href="{{ p.url }}">{{ p.title }}</a></li>
{% endif %}
{% endfor %}
<li class="active">{{ self.title }}</li>
</ul>
{% endif %}
</div>
@blerdijankoliqi
Copy link

Thank you!

@simzam
Copy link

simzam commented Nov 19, 2023

Really nice! Thanks.

@ch12i5
Copy link

ch12i5 commented Mar 4, 2024

This is a super helpful snippet, thank you! :)

@Nigel2392
Copy link

Nigel2392 commented Apr 18, 2024

As of Wagtail 6.1 this should get updated to populate an array inside of a view; to then use in a template.
For the routed page; this will make sure the query count will be zero. The database should NOT be hit.

Rough sketch:

class MyPage(...):
    def get_context(self, ...):
        context = super().get_context(...)
        breadcrumbs = []
        
        page = self
        while page.get_parent() is not None:
            if page.is_root():
                break
            # Note how we do not add self.
            page = page.get_parent()
            breadcrumbs.append(page)

        breadcrumbs.reverse()
        context["breadcrumbs"] = breadcrumbs
        return context

And then in the template:

<div class="breadcrumb-content">
    {% if breadcrumbs|length > 1 %}
        <ul class="breadcrumb">
            {% for p in breadcrumbs %}
                <li><a href="{{ p.url }}">{{ p.title }}</a></li>
            {% endfor %}

            <li class="active">{{ self.title }}</li>
        </ul>
    {% endif %}
</div>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment