Phil
Phil

Reputation: 515

Umbraco foreach children of a child page

I have news posts within a news page within a homepage on my content structure

Example:

Homepage
- News
-- News Posts

I'm looking to have some of the news feed on my homepage in a foreach statement. In my head it should be as simple as:

@foreach (var homenews in CurrentPage.Children.Children)
{
     if (homenews.Name == "News Post")
     {
         //Do some stuff//
     }
}

Obviously that doesn't work so has anybody got any ideas? Thanks

Upvotes: 4

Views: 15839

Answers (4)

Phil
Phil

Reputation: 515

I ended up getting the news page by its id and then getting it's children from there. The below code worked for me. Thanks guys.

@{
    var node = Umbraco.Content(1094);    
    <p>@node.Id</p> // output is 1094  
    foreach (var item in node.Children.Where("Visible").Take(3))

    {

         <p>@item.exampleText</p>

    }
    }

Upvotes: 3

Stef
Stef

Reputation: 341

You need to reference the required node by NodeTypeAlias of it's Document Type.

So assuming the alias of the DocType of your News Posts is “NewsPosts” then...

@foreach (var homenews in @Model.Descendants().Where("NodeTypeAlias == \"NewsPosts\"")).Take(3)
{       
    <p>@homenews.Name<p>
}   

...should return the name of the first 3 news posts.

Upvotes: 1

mjroodt
mjroodt

Reputation: 3313

I had the exact scenario, this is how I got mine working. NodeByID was very useful nad -1 indicates the root

@foreach(var item in Model.NodeById(-1).Children)
    {
string itemName = item.Name;
switch(itemName)
{
    case "News":
        @* News *@
    <div id="News"> 
      <h3><a href="@item.Url">@item.Name</a></h3>
   @foreach (var newsPost in item.Children.OrderBy("UpdateDate desc").Take(4).Items)
        {
            <p>
            <a href="@newsPost.Url">@newsPost.Title</a>
             </p>
        }

    </div>
   }
}

Upvotes: 0

Digbyswift
Digbyswift

Reputation: 10400

When you're walking the tree you have to remember that a property (or method) like Children or Descendants() will return a collection of objects, so you can't just call Children of a collection. You can only call Children on a single object.

You can find the correct child of the homepage by using something like var newsPage = CurrentPage.Children.Where(x => x.DocumentTypeAlias == "NewsListingPage") and then extract the children of that page.

Upvotes: 4

Related Questions