I'm trying to work out what level a block is in a Block hierarchy.
e.g. a page with a block within a block would be level 2.
This is so I might be able set up the HTML Header elements so they are correct. So in the example above the page would have a
Anyone got any ideas on how I could approach this?
Perhaps someone has a better idea, but you could just fetch blocks parents and stop counting when you get to a parent of type PageData?
Something like this (untested though):
public static class TreeExtensions
public static int GetBlockLevel(this IContent block)
var currentParent = block.GetParent();
var level = 1;
while (!(currentParent is PageData))
currentParent = currentParent.GetParent();
public static IContent GetParent(this IContent content)
var contentLoader = ServiceLocator.Current.GetInstance<IContentLoader>()''
var parentContent = contentLoader.Get<IContent>(content.ParentLink);
Hope this helps,
Thanks for your response! You're code mostly worked but as the block was created in the Block library it's parent was the Library Folder (EPiServer.Core.ContentFolder -> EPiServer.Core.ContentFolder -> Root). Possibly the way I passed it from the controller?
public override ActionResult Index(SliderItemBlock currentBlock)
var blockContent = currentBlock as IContent;
var blockLevel = blockContent.GetBlockLevel();
return PartialView("~/Views/Shared/Blocks/ContentTiles/SliderItemBlock.cshtml", currentBlock);
I'm guessing library blocks are just references when they are used in a page or block. Not sure if there's a way around this but I definately learned from trying this.
I don't think it's the way you are calling it, but rather where you are calling it. Are you debugging this for block preview in edit mode or where the block is actually rendered in view mode? Is it a standard shared block added to a content area on the page or another block which is eventually in a contentarea on a page?
I get correct results when debugging GetParent from a viewmode of a page where block is.
Do you have 7.1 or 7.5+?
Now I remember is that I had a similar question back when we started with EPiServer 7. At that point, I also got the folder structure. See this answer from Johan.
But, if you have the possibility to upgrade to latest, I would strongly advise so. It's not only due to this issue, but also lots of things are better and lots of bugs are fixed in the meantime. Loads of new features are coming as well :)
Thanks again for the response. We are currently running EPiServer 7.10 so it's possibly not fixed in this version. I will upgrade the site to the latest and let you know how it goes.