使用时:
@Model.AncestorOrSelf(3)
在 Umbraco 的 .cshtml 模板中,这可能会将节点遍历限制为 3 个级别。这是正确的,如果是这样,任何人都可以确认当前节点的索引是否为零?
使用时:
@Model.AncestorOrSelf(3)
在 Umbraco 的 .cshtml 模板中,这可能会将节点遍历限制为 3 个级别。这是正确的,如果是这样,任何人都可以确认当前节点的索引是否为零?
@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)
添加到 SiddharthP 的答案中,我认为 OP 可能正在寻找 @CurrentPage.Up(int) 方法 - 这是从当前级别向上遍历树指定数量的级别。
因此,如果您想要当前节点的祖父 - @CurrentPage.Up(2) 或 @Model.Content.Up(2) 用于强类型版本。
可以将其想象为 Ancestor 从内容树的根向下开始,向上从您要去的根开始。
我认为令人困惑的一点是您使用 CurrentPage 对象,但开始从顶部根节点向 CurrentPage 遍历。当我们想到人类中的祖先时,我们并不是从一开始就开始的!
如果我对代码的理解是正确的, .AncestorOrSelf(int) 将返回参数中给定级别的节点的祖先(或自身) 。
public DynamicNode AncestorOrSelf(int level)
{
return AncestorOrSelf(node => node.Level == level);
}
public DynamicNode AncestorOrSelf(Func<DynamicNode, bool> func)
{
if (func(this)) return this;
var content = this;
while (content.Level > 1) // while we have a parent, consider the parent
{
// see note in .Parent - strange things can happen
var parent = content.Parent;
if (parent == content) return null;
content = parent;
if (func(content))
return content;
}
return null;
}
希望我已经正确理解了这一点,并且这会有所帮助。