KNOWLEDGE BASE

Grouping nodes in Umbraco Razor


Have you ever been in the situation where you need to loop through a list of nodes but arange them in groups of 2, 4, 6 etc

You want to have a fluid layout and display your nodes in groups of two repeating down the page:

 

<div class="row-fluid">
<div class="span6">
<img src="/image.png>
<h3><a href="#">Link to page</a></h3>
</div>
<div class="span6">
<img src="/image.png>
<h3><a href="#">Link to page</a></h3>
</div>
</div>

 

The problem is if you use a standard foreach loop, you will get repeating content for each span6 element - not what you want. Ideally you need to group them but not sure how - see the solution below.

@using Umbraco.Core
@using umbraco.MacroEngines
@inherits DynamicNodeContext
@{
var r = new Random();
constintnumberOfItems = 6;
var startNode = new DynamicNode(Model.Id).Descendants("StandardPage")
.Items.Where(x => x.Visible).OrderBy(x => r.Next()).Take(numberOfItems).ToList();
}

 

<h2 class="page">Section Title</h2>
@foreach (var page in startNode.InGroupsOf(2))
{
<div class="row-fluid">
@foreach (var item inpage)
{
<div class="span6">
<img src="/empty.png" alt="@item.Name" />
<h3><a href="@item.Url">@item.Name</a></h3>
</div>
}
</div>
}
</div>

Need an Umbraco Master?

Here at Simon Antony, we have an in house certified Umbraco Grand Master available for hire. Got a problem with your site, need architecture advice, give us a call to speak to Simon directly and see how we can help

Contact Simon Today!