ManxJason
ManxJason

Reputation: 940

Umbraco & Razor: If CurrentPage/Model is a Child, condition

My navigation/node structure is as follows:

Home
--About us
--Our Services
-----Finance
-----Insurance

My current code loops through the nodes and lists them in an . When the 'CurrentPage' has children, the menu includes the children.

The problem with this loop is that when one of those children (Finance or Insurance) is the 'CurrentPage', the 'if' condition on 'Our Services' node fails as th CurrentPage no longer has children, therefore 'Finance' and 'Insurance' now longer remain in the menu.

I want to add to me 'if', an '||' clause which would basically say 'or CurrentPage is a child node'

Code below thanks

<ul>
    @foreach (var page in @CurrentPage.AncestorOrSelf(1).Children)
    {
        <li class="menuItems @(page.IsAncestorOrSelf(CurrentPage) ? "selected" : null)">
            <a href="@page.Url">@page.Name test</a>
        </li>


        if (@CurrentPage.Children.Count() > 0)
        {                
            foreach (var childPage in page.Children)
            {                    
                <li class="menuItems menuChildItems @(childPage.IsAncestorOrSelf(CurrentPage) ? "selected" : null)">
                    <a href="@childPage.Url">@childPage.Name</a>
                </li>
            }
        }

    }
</ul>

Upvotes: 2

Views: 4409

Answers (1)

Morten OC
Morten OC

Reputation: 1784

  1. The first foreach should be from your Home. (Is your Home at level 1?)

  2. There is no need to do the if(has children) check, because if there isn't any children, it will not loop.

Do you only want 2 levels of menus? If so, do it like this:

<ul>
    @foreach (var page in CurrentPage.AncestorOrSelf(1).Children)
    {
        <li class="menuItems @(page.Id == CurrentPage.Id ? "selected" : "")">
            <a href="@page.Url">@page.Name test</a>
        </li>

        @if(CurrentPage.Id == page.Id || CurrentPage.Parent.Id == page.Id)
        {
            foreach (var childPage in page.Children)
            {                    
                <li class="menuItems menuChildItems @(childPage.Id == CurrentPage.Id ? "selected" : "")">
                    <a href="@childPage.Url">@childPage.Name</a>
                </li>
            }
        }
    }
</ul>

Upvotes: 2

Related Questions