在Umbraco 7.x中按名称获取子节点

时间:2014-02-18 19:42:11

标签: umbraco7

我有一个页面,其中有一个名为“Widgets”的子节点。我想在我的页面模板中的某个部分渲染该子项的模板。目前,我这样做:

@{
    foreach (var child in CurrentPage.Children)
    {
        if (child.Name == "Widgets")
        {
            @Umbraco.RenderTemplate(child.Id)
        }
    }
}

有没有办法避免像这样绕过孩子?

我也发现我可以这样做:

@{
    @Umbraco.RenderTemplate(
        Model.Content.Children
            .Where(x => x.Name == "Widgets")
            .Select(x => x.Id)
            .FirstOrDefault())
}

但我真的希望有更简洁的方法来做到这一点,因为我可能想在给定页面上的几个地方做这件事。

3 个答案:

答案 0 :(得分:1)

是的,你可以使用Examine。

但是,我强烈反对这种做法,因为用户可以更改节点的名称,从而可能会破坏您的代码。

我会创建一个特殊的文档类型,并使用文档类型搜索节点。有几种(快速)方法可以做到这一点:

@Umbraco.ContentByXPath("//MyDocType") // this returns a dynamic variable
@Umbraco.TypedContentSingleByXPath("//MyDocType") // this returns a typed objects
@Model.Content.Descendants("MyDocType")
// and many other ways

答案 1 :(得分:0)

对同一个接受的答案的想法是肯定的

以下代码为我工作。

 var currentPageNode = Library.NodeById(@Model.Id);

  @if(@currentPageNode.NodeTypeAlias == "ContactMst")
   {
              <div>Display respective data...</div>
  }

答案 2 :(得分:0)

提到不好的做法。而是按类型查找节点,并在代码中使用文档类型的别名。如果由于某种原因你需要一个特定的节点,而是给它一个属性并寻找属性。下面的示例代码

if (Model.Content.Children.Any())
{
    if (Model.Content.Children.Where(x => x.DocumentTypeAlias.Equals("aliasOfCorrespondingDocumentType")).Any())
    {
        // gives you the child nodes underneath the current page of particular document type with alias "aliasOfCorrespondingDocumentType"
        IEnumerable<IPublishedContent> childNodes = Model.Content.Children.Where(x => x.DocumentTypeAlias.Equals("aliasOfCorrespondingDocumentType"));

        foreach (IPublishedContent childNode in childNodes)
        {
            // check if this child node has your property
            if (childNode.HasValue("aliasOfYourProperty"))
            {
                // get the property value
                string myProp = childNode.aliasOfYourProperty.ToString();

                // continue what you need to do
            }
        }
    }
}