Search code examples
htmlforeachumbraco

How to add a class to the first child in foreach in Umbraco


I am making a dynamic Bootstrap column in Umbraco. How can I assign class "col-md-offset-1" only to the first child in the column col-md-2?

@{
   foreach (IPublishedContent list in homeList.Where(x => x.IsVisible()))
   {
      string text = list.GetPropertyValue<string>("listText");
      string style = list.GetPropertyValue<string>("listItemStyle");

      <div class="col-md-2 text-center">
         <div class="circle"><i class="@style"></i></div>
            <p>@text</p>
      </div>
   }
 }

Solution

  • You can try something along the lines of:

    @{
       var additionalClassForFirstItem = "col-md-offset-1";
       foreach (IPublishedContent list in homeList.Where(x => x.IsVisible()))
       {
          string text = list.GetPropertyValue<string>("listText");
          string style = list.GetPropertyValue<string>("listItemStyle");
    
          <div class="col-md-2 text-center @{additionalClassForFirstItem}">
             <div class="circle"><i class="@style"></i></div>
                <p>@text</p>
          </div>
          if (!string.IsNullOrEmpty(additionalClassForFirstItem)) {
             additionalClassForFirstItem = string.Empty;
          }
       }
     }
    

    or iterate for using integer variable, like for (int i = 1, ..) , and check if it is = 1