How do you make breadcrumbs in your Twig templates for Craft 3?
Unfortunately I found examples only for Craft 2
Craft CMS Stack Exchange is a question and answer site for administrators, end users, developers and designers for Craft CMS. It only takes a minute to sign up.
Sign up to join this communityHow do you make breadcrumbs in your Twig templates for Craft 3?
Unfortunately I found examples only for Craft 2
When it comes to creating breadcrumbs, I can only offer advice when doing so within a structure.
Craft 3 still has .ancestors
available on an entry so you can do:
{% set breadcrumbs = entry.ancestors.all() %}
Then check the length and loop through the ancestors for the structure entry.
{% if breadcrumbs|length %}
<ul class="breadcrumbs">
<li><a href="{{ siteUrl }}">Home</a></li>
{% for crumb in breadcrumbs %}
<li><a href="{{ crumb.url }}">{{ crumb.title }}</a></li>
{% endfor %}
<li>{{ entry.title }}</li>
</ul>
{% endif %}
Then just add a little CSS to style as you choose.
<style>
.breadcrumbs {
list-style: none;
padding: 0;
margin: 0;
}
.breadcrumbs li { display: inline; }
.breadcrumbs li+li:before {
padding: 8px;
color: black;
content: "\000BB";
}
</style>
This would use »
between each entry.
Home » First Article » Another Article » Grandchild Article
default([])
good for? The default return value from all
is an empty array. Could you please explain the sense of that filter?
Jun 11, 2018 at 5:12
Here is something I'm using. It traverses the url segments and loads the associated entry to build the breadcrumb (using Bootstrap 4.x) - Not sure this is the most efficient/correct way, but hopefully this helps someone:
{% if craft.request.segments %}
<div class="container">
<div class="row">
<div class="col-sm-12">
<nav aria-label="breadcrumb">
<ol class="breadcrumb">
<li class="breadcrumb-item"><a href="{{ siteUrl }}">Home</a></li>
{% for segment in craft.request.segments %}
{% set segmentEntries = craft.entries.slug(segment).find() %}
{% for segmentEntry in segmentEntries %}
{% if segmentEntry.id == entry.id %}
<li class="breadcrumb-item">{{ segmentEntry.title }}</li>
{% else %}
<li class="breadcrumb-item"><a href="{{ segmentEntry.url }}">{{ segmentEntry.title }}</a></li>
{% endif %}
{% endfor %}
{% endfor %}
</ol>
</nav>
</div>
</div>
</div>
{% endif %}
Built using code from this thread as inspiration: What is the best way to create breadcrumbs based on a structure?
The verbb navigation plugin has a good breadcrumbs service:
Here is a link to the breadcrumb template component for Craft CMS 3. It is automatically created from URL structure.
http://craftsnippets.com/articles/breadcrumb-created-from-url-for-craft-cms