Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Umbraco AncestorOrSelf(int) - what does it do?

Tags:

umbraco

When using:

@Model.AncestorOrSelf(3)

In a .cshtml template in Umbraco, this would presumably limit the node traversal to 3 levels. Is this correct, and if so can anyone also confirm if the current node has the index zero?

like image 649
Chris Halcrow Avatar asked Nov 11 '13 21:11

Chris Halcrow


1 Answers

@Model.AncestorOrSelf(3)

Model.Content is the current page that we're on. AncestorsOrSelf is all of the ancestors this page has in the tree. (level) means: go up to level 1/2/3/... and stop looking for more ancestors when you get there.

Above is the comment that you get with Umbraco 7.x rc version.

Take an example of the content tree below that is kind of similar to that you normally see in contents section in umbraco admin area:

Each content document has a level and by default it starts with 1.

In a .cshtml template in Umbraco, this would presumably limit the node traversal to 3 levels

As you can see in the example below, the level gets on increasing - level + 1. so, it starts by 1 and then just go on adding 1 to your sub levels.

- Content
 -- Home (level = 1)
   -- About Us (level = 2)
   -- Contact Us (level = 2)
   -- News Area (level = 2)
     -- News Item 1 (level = 3)
     -- News Item 2 (level = 3)
 -- Other Node (level = 1)

So when you mention 3 as parameter for AncestorOrSelf, you are asking to move to 3rd level in the tree from the current element that can be any document/partial view and stop looking for any more ancestors when its found.

AncestorOrSelf(level) returns a single item which if of type DynamicPublishContent i.e. you will have access to many properties like id, name, url, etc.

@CurrentPage.AncestorOrSelf(1)
// based on content structure above, the above statement will give you an item - Home.

It is basically for fetching ancestors by level, doesn't matter what your current level or currentpage object is.

For example, if you want to create a navigation in your main layout so as to share it on all pages of your site, you will do something like this in your template:

<ul>
 @foreach(var page in @CurrentPage.AncestorOrSelf(1).Children)
 {
   <li><a href="@page.Url">@page.Name</a></li>
 }
</ul>

Based on our example, it will give you:

About Us, Contact Us, News Area (in list form and with proper links)

like image 110
Siddharth Pandey Avatar answered Nov 02 '22 21:11

Siddharth Pandey