Copied to clipboard

Flag this post as spam?

This post will be reported to the moderators as potential spam to be looked at


  • Phillip Turner 98 posts 412 karma points
    Apr 09, 2014 @ 16:48
    Phillip Turner
    0

    Splitting a UL list in Razor

    Please see the working code below:

    @inherits Umbraco.Web.Mvc.UmbracoTemplatePage
    @{
        var selection = CurrentPage.AncestorOrSelf().Children.Where("showInFooter").OrderBy("Name");
        int max = 8;
    }
    <ul>
    @for (int i = 0; i < selection.Count(); i++)
    {
        var page = selection[i];
        <li>@page.Name</li>
    }
    </ul>
    

    I also know I can do it this way:

    <ul>
    @foreach (var page in selection) {
        <li>@page.Name</li>
    }
    </ul>
    

    but what I am trying to achieve is when i == max, I want to split the UL into a new list. Problem is, Razor renders the following error because its seeing unexpected closing of UL and opening of UL that is not in the { } block.

    enter image description here

    My code block:

    <ul>
    @for (int i = 0; i < selection.Count(); i++)
    {
        var page = selection[i];
    
    if (i == max)
    {
            </ul>
        <ul>
    }
    
    <li>@page.Name</li>
    }
    </ul>
    

    Many thanks!

    Phillip

  • Carsten Fallesen 35 posts 154 karma points
    Apr 09, 2014 @ 21:09
    Carsten Fallesen
    102

    Hi Phillip,

    I believe the easiest way to achieve what you want is to use the InGroupsOf() method:

    @foreach(var group in selection.InGroupsOf(8))
    {
    <ul>
    @foreach(var item in group)
    {
    <li>@item.Name</li>
    }
    </ul>

    I haven't tested the code, but it should be something like this.

    /Carsten

  • Phillip Turner 98 posts 412 karma points
    Apr 09, 2014 @ 21:34
    Phillip Turner
    0

    Thanks Carsten. That did work and alot more elegant than my version

    @inherits Umbraco.Web.Mvc.UmbracoTemplatePage
    @{
        var selection = CurrentPage.AncestorOrSelf().Children.Where("showInFooter").OrderBy("Name");
        int max = 8;
        string HtmlBlock = "</ul></div><div class=\"site-map\"><ul>";
        System.Web.HtmlString html = new HtmlString(HtmlBlock);
    }
    <div class="site-map">
    <ul>
    @for (int i = 0; i < selection.Count(); i++)
    {
        var page = selection[i];
    
        if (i == max)
        {
            @html
        }
    
        <li>@page.Name</li>
    }
    </ul>
    </div>  
    

    Phillip

Please Sign in or register to post replies

Write your reply to:

Draft