Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Cover image for Breadcrumb created from URL for Craft CMS
Piotr Pogorzelski
Piotr Pogorzelski

Posted on • Originally published atcraftsnippets.com

     

Breadcrumb created from URL for Craft CMS

Thisarticle was originally posted oncraftsnippets.com, blog about Craft CMS. Head there for more Craft-related articles and ready to use template components.


Component overview

This template component can be dropped into any project - itworks out of the box, without any modifications. Here are it's features summed up:

  • Component is styled usingbulma classes.
  • It has googlestructured data attributes to improve your SEO.
  • It also has properARIA attributes. ARIA stands forAccessible Rich Internet Applications - it's standard which seeks to help people with disabilities navigate websites using tools like screen readers.
  • Breadcrumb will only show up if multiple links exist, since breadcrumb with just one link is not really useful.

Breadcrumb component itself:

{# v3 #}{# http://craftsnippets.com/articles/breadcrumb-created-from-url-for-craft-cms #}{# settings #}{%setnonElementLinks=false%}{# populate breadcrumbLinks array if no array of links was provided #}{%ifbreadcrumbLinksisnotdefined%}{%setbreadcrumbLinks=[]%}{# home #}{%sethome=craft.app.getElements().getElementByUri('__home__',currentSite.id)%}{%setbreadcrumbLinks=breadcrumbLinks|merge([{url:home.url??alias(currentSite.baseUrl),title:home.title??'homepage'|t,}])%}{# get elements #}{%setsegments=craft.app.request.segments%}{%forsegmentinsegments%}{%seturiPart=segments[0:loop.index]|join('/')|literal%}{%setelement=craft.app.elements.getElementByUri(uriPart,currentSite.id)%}{%ifelement%}{%setbreadcrumbLinks=breadcrumbLinks|merge([{url:element.url,title:element.title,}])%}{%elseifnonElementLinks%}{%setbreadcrumbLinks=breadcrumbLinks|merge([{url:url(uriPart),title:segment|t,}])%}{%endif%}{%endfor%}{%endif%}{# render breadcrumb #}{%ifbreadcrumbLinks|length>1%}<navclass="breadcrumb"aria-label="{{'breadcrumbs'|t}}"><ulitemscopeitemtype="http://schema.org/BreadcrumbList">{%forlinkinbreadcrumbLinks%}<liclass="{{loop.last?'is-active'}}"{{loop.last?'aria-current="page"'}}itemprop="itemListElement"itemscopeitemtype="http://schema.org/ListItem"><ahref="{{link.url}}"itemtype="http://schema.org/Thing"itemprop="item"><spanitemprop="name">{{link.title}}</span></a></li>{%endfor%}</ul></nav>{%endif%}
Enter fullscreen modeExit fullscreen mode

How does it work?

For each URL segment, element query usinggetElementByUri method is performed. This query uses URI parameter that is composed ofthis segment andall segments preceding it. If the query is successful,title of the returned object is used as specific breadcrumb link text value.getElementByUri will go throughall elements that haveURI attribute - entries, categories and even custom ones added by plugins.

First breadcrumb link is not represented by URL segment - it ishomepage link. It is associated with entry with empty URI, queried by special slug__home__.title of that entry will be used as text value of link. If no such entry exists, stringhomepage passed through translation filter will be used instead.

Custom route links

IfgetElementByUri method returns nothing, it means that URL segment is not associated with entry, category or any other custom element page. Most likely it represents some custom URL route. In such a situation, you can do one of these things:

  • Set up an array of links yourself and pass it manually to the component asbreadcrumbLinks - like this:{% include 'breadcrumb' with {breadcrumbLinks: breadcrumbLinks} %}. If component receives such array, it will not generate links itself but use these passed to it.
  • Set variablenonElementLinks at begining of the component totrue. This will cause links not associated with elements pages to be appended to the breadcrumb. Their text values will be taken from URL segment and passed trough|t filter so you can set them up instatic translations.

Breadcrumb with Seomatic

If you are already usingSeomatic on your website, you can use it's built-in functionality to get data required to render links. Here's breadcrumb component adjusted for Seomatic:

{%setbreadcrumbLinks=seomatic.jsonLd.get('breadcrumbList').itemListElement%}{%ifbreadcrumbLinks|length>1%}<navclass="breadcrumb"aria-label="{{'breadcrumbs'|t}}"><ul>{%forlinkinbreadcrumbLinks%}<liclass="{{loop.last?'is-active'}}"{{loop.last?'aria-current="page"'}}><ahref="{{link.item['@id']}}"><spanitemprop="name">{{link.item['name']}}</span></a></li>{%endfor%}</ul></nav>{%endif%}
Enter fullscreen modeExit fullscreen mode

Note that this version of breadcrumb is stripped of it's structured data attributes - Seomatic renders proper JSON-LD code for breadcrumb which does the same job.

Seomatic breadcrumb also doesn't include links not related to element pages. To learn how to add them to breadcrumb, head toSeomatic docs and look for "To entirely replace the existing BreadcrumbList on a page".

Why is such breacrumb component useful?

Craft CMS allows us to build websites with URLs consisting of multiple segments. If your website has many types of categories and sections, your URL logic can get quite complicated. For example, let's consider such URL for article page:

category-list/1-level-category/2-level-category/article-page

Here are URL settings of various sections and categories needed to achieve such URL structure:

  • Article page section needs to havecategoryField category field and such url setings:{categoryField.last.uri}/{slug}.
  • Categories have multiple levels, so for category group, URL settings would be:{parent.uri ?? craft.entries.section('category_list').one.uri}/{slug}.
  • Category list is single type section, so it only needs hardcoded entry title:category-list.

As you can see, these URL settings use element queries and conditional operators. Wecould reproduce all this logic within breadcrumb component in Twig. But we don't need to. Remember -Don't Repeat Yourself.

Breadcrumb plugin

As an alternative to breadcrumb template component described in this article, you can useBreadcrumb plugin. It works pretty much the same while featuring few useful configuration options, like:

  • customising title of first breadcrumb link directing to homepage.
  • Setting maximum amount of breadcrumb links
  • Skipping specific segments

Just like with all plugins - before installing it consider if you really need it. Keep in mind that each plugin adds additional level of complexity to your website.

Article update history

  • 1 july 2019 - breadcrumb homepage link is now created from homepage url orcurrentSite.baseUrl passed throughalias function - to take into account situation when site base url is set to@web.

Top comments(0)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

  • Joined

More fromPiotr Pogorzelski

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp