Copied to clipboard

Flag this post as spam?

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


  • Daniel Larsen 116 posts 381 karma points
    Aug 20, 2013 @ 13:35
    Daniel Larsen
    0

    Add class to two li's, then skip two

    Hi, I want to make a list, where item 0 and 1 has a class, item 2 and 3 dont, and item 4 and 5 has class etc.

    This is what I have working, but it is not very dynamic.

    @foreach (var i in Model.Descendants())
    {
        if(i.Index() == 0 || i.Index() == 1 || i.Index() == 4 || i.Index() == 5)
        {
            <li class="odd">@i.Name</li>
        }
        else
        {
            <li>@i.Name</li>
        }
    }
    

    Can you please help me :-)

  • Andy Butland 422 posts 2334 karma points MVP 4x hq c-trib
    Aug 20, 2013 @ 15:03
    Andy Butland
    0

    There might be a nicer way I can't yet see, but you could do this with a couple of variables.  Try this (not tested, but I think it'll work):

    @{
        var groupCount = 0;
        var oddFlag = true; 
    }
    @foreach (var i in Model.Descendants())
    {
        if (oddFlag)
        {
            <li class="odd">@i.Name</li>
        }
        else
        {
            <li>@i.Name</li>
        }
    
        groupCount++;
        if (groupCount == 2) 
        {
           groupCount = 0;
           oddFlag = !oddFlag;
        }
    }
  • Funka! 398 posts 661 karma points
    Aug 21, 2013 @ 03:06
    Funka!
    100

    I think you can use the "InGroupsOf" method to help out here? I don't actually know if this will work, so be warned: Untested code ahead!

    string className = "";
    @foreach (var g in Model.Descendants().InGroupsOf(2))
    {
        className = (className == "") ? "odd" : "";         // toggle the className!
        foreach (var i in g)
        {
            <li class="@className">@i.Name</li>
        }
    }
    

    Best of luck to you!

  • Daniel Larsen 116 posts 381 karma points
    Aug 22, 2013 @ 10:00
    Daniel Larsen
    0

    Thank you both. I had a working solution, but your solution is much simpler.

    Thanks! :-D

  • Funka! 398 posts 661 karma points
    Aug 22, 2013 @ 19:36
    Funka!
    0

    [deleted]

Please Sign in or register to post replies

Write your reply to:

Draft