Breadcrumbs help your visitors understand where they are on your website and, more importantly, how they can get back to parent pages. Some people love breadcrumbs, some hate them, however, it has been proven that they help to keep visitors on a site. Luckily, creating a breadcrumb in Umbraco is really easy. In today's guide, I'm going to quickly cover all the code that you will need to write in order to build a breadcrumb yourself!
Getting The Data
When getting data out of Umbraco, you will want to get the data out of the cache. This is done using the UmbracoHelper
. UmbracoHelper
returns Umbraco content of type IPublishedContent
. When you work with IPublishedContent
you will know that things will be quick! The first snippet of code you will need to write will be a query to get a list of all the parent pages from the current page, up until the homepage. This is possible using the Ancestors()
method, like so:
By default, Ancestors()
will exclude the current page from these results. If you want to include the current page, you can do this instead:
I'm also going to assume you're using MVC and route hijacking when you are constructing your page. When using route hijacking, you will have a custom controller. To follow good practices, you should return and pass a view model from your controller into your view to pass the data in a nice and decoupled way. The code to create a view model for a breadcrumb is simple:
In most good breadcrumbs, there is usually some form of separator between the links. Unless we add some extra logic (or do it in CSS), the separator will display after the current page as well, e.g.
homepage
➡ landing page
➡ current page
One thing to consider when using separators is the last item! We do not want a >
to display after the current page is rendered within the breadcrumb, as it will look broken! We can prevent this from occurring, using a total count property. The rest of the code is simply exposing the items in the breadcrumb, e.g. IPublishedContent
and rendering them onto the page. Do not forget to add a using
reference to Umbraco.Web
, otherwise, Visual Studio will moan at you. Last up is the HTML to render the page, this code is the easy bit:
Loop through the items in the breadcrumb list and spit out some HTML. That covers everything you need to create a simple breadcrumb in Umbraco v7 or v8. Happy Coding 🤘