It’s one of the most common modules you will create as web developer and there are many ways to implement one. The humble breadcrumb is a useful navigational tool, allowing users to quickly go up the content tree without having to rely on the back button or the navigation again. This post will show you how to create a Sitecore breadcrumb, allowing you to extend on the baseline code.
During this post I will go through how to implement some simple breadcrumb code using Sitecore.
Here is the starting point:
List<Item> breadcrumbItems = Sitecore.Context.Item.Paths.LongID
.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries)
.Select(x => Sitecore.Context.Database.GetItem(x))
.Where(x => !string.IsNullOrEmpty(x.Fields[Sitecore.FieldIDs.LayoutField]?.Value));
From the code above you can see we use the current context item’s LongID
. In summary, this is a long string containing all the ancestor’s IDs and the current item’s ID, separated by slashes (/).
For instance: /{11111111-1111-1111-1111-111111111111}/{0DE95AE4-41AB-4D01-9EB0-67441B7C2450}/{110D559F-DEA5-42EA-9C1C-8A5DF7E70EF9}
Secondly, we are splitting this long string into a list of strings using the Split()
LINQ method.
The third line converts these ID strings into their respective Sitecore items using the GetItem()
method inside the Select()
.
The Where()
statement is important as it filters out items that do not have presentation details set. These are usually your organisational items such as folders. Remove this line if you want to include these.
You could now use this variable to display a list of breadcrumb items on the front end of your website as well as populating JSON schema.
Getting the Item’s URL When You Create a Sitecore Breadcrumb
If you want to do either of these things you will likely need to get the URL for the item whilst iterating through the list. This can be done with the following method:
string itemUrl = LinkManager.GetItemUrl(item, new UrlOptions { AlwaysIncludeServerUrl = true});
There are lots of other properties in the UrlOptions
you can set, so be sure to explore that object. I have set the AlwaysIncludeServerUrl
to true so that the fully qualified URL is returned, not just the relative path.
Thank you for reading my post and hopefully the information has shown you how to create a Sitecore breadcrumb. You can check out more of my posts here and feel free to contact me.
Happy Sitecoring! 🙂