2014-02-18 27 views
1

我有一个具有名为“Widgets”的子节点的页面。我想在我的页面模板的某个部分渲染该孩子的模板。目前,我这样做:在Umbraco 7.x中按名称获取子节点

@{ 
    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()) 
} 

但我真的很希望有一个更简洁的方式来做到这一点,因为我可能要做到这一点在几个地方在特定网页上。

回答

1

是的,你可以使用检查。

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

我会创建一个特殊的文档类型,并使用文档类型搜索节点。有几个(快)的方式来做到这一点:在接受的答案

同样的想法,下面的代码为我工作

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

我真的没有问题需要特定的小部件命名约定,因为这里的用例是私人和每个站点。试图找出完成任务的最简单的方式。 – Chris

+1

仍认为它不能比我给出的例子少冗长和更安全。如果您想在相同的设置中使用较少的代码:Model.Content.CurrentPage.First(x => x.Name ==“Widget”)。Id – dampee

+0

糟糕。当然,CurrentPage应该是Childeren。这就是说,如果你想使用动态的话,你可以用CurrentPage替换Model.Content。 – dampee

0

是。

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

    @if(@currentPageNode.NodeTypeAlias == "ContactMst") 
    { 
       <div>Display respective data...</div> 
    } 
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 
      } 
     } 
    } 
}