Breadcrumbs help your visitors understand where they are on your website and, more importantly, how they can get back to previous pages. Some people love breadcrumbs, some hate them, but they do help keep your visitors on your 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 need in order to build a breadcrumb.
Getting The Data
First, we need to get the data out of Umbraco. In this tutorial I'm assuming you want to get the data out of the cache, so we'll be working with the UmbracoHelper and IPublished content.
The first snippet of code we will need is to get a list of all the parent pages in the tree from the current page, up until the homepage. We do that with the Ancestors() method, like so:
Ancestors() will return a list of all of the pages' ancestors, back to the homepage (excluding the current page). If you want to include the current page as well you can do this instead:
I'm also going to assume you're using MVC and route hijacking. In this situation, you'll need a view model to pass the data from your controller to your view. The code for this is simply
I've gone over the getting data from Umbraco bit above, so let's quickly talk about the other parts. In most good breadcrumbs, there's usually a separator between the links. Unless we add some extra logic, the separator will display after the current page as well, e.g. homepage > landing page -> current page >.
To strip out the last separator we need a total count property. This will allow us to add a '>' between each breadcrumb, identify when we're rendering the last item and omit it. The rest of the code is simply moving the IPublishedContent into a Breadcrumb object. In MVC it's good practice to only expose the minimum amount of properties in your view model. Also, don't 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's the easy bit, loop through a list and spit out some HTML. Well, that covers everything you need to create a breadcrumb in Umbraco, enjoy!