mmmoustache
mmmoustache

Reputation: 2323

Iterate through Umbraco nodes and group into two's using Razor

I'm trying to iterate through my Umbraco node tree, using Razor, and I'd like to organise the results into groups of two within a simple HTML list but I can't think of a solution.

For example, here's my Umbraco node tree in it's simplest form:

- Node 1
- Node 2
- Node 3
- Node 4
- Node 5
- Node 6
- Node 7
- Node 8

And I'm trying to achieve the following:

<ul>
    <li>
        <span>Node 1</span>
        <span>Node 2</span>
    </li>
    <li>
        <span>Node 3</span>
        <span>Node 4</span>
    </li>
    <li>
        <span>Node 5</span>
        <span>Node 6</span>
    </li>
    <li>
        <span>Node 7</span>
        <span>Node 8</span>
    </li>
</ul>

Does anyone know how this can be achieved?

Upvotes: 0

Views: 1815

Answers (1)

Douglas Ludlow
Douglas Ludlow

Reputation: 10942

Using the undocumented InGroupsOf method, you can accomplish this fairly easily:

@inherits umbraco.MacroEngines.DynamicNodeContext
@{
    <ul>
    @foreach (var group in Model.Children.InGroupsOf(2))
    {
        <li>
        @foreach (var node in group)
        {
            <span>@node.Name</span> 
        }
        </li>
    }
    </ul>
}

More InGroupsOf examples:

Upvotes: 5

Related Questions