Wrap every 3 elements with HTML Wrapper code in a C # ForEach loop
I need to build my HTML code structure in C # code. The code has inserted an HTML element that spans 3 columns in 12 Row columns (I'm using the Zurb Foundation).
I am iterating over a set of elements in a foreach loop.
I want to add some code <div class='row'>[item html code here]</div>
that will wrap three columns.
The product code looks something like this:
<div class='column large-4 medium-4- small-12' >some content</div>
What logic should I use (C #) to be able to inject the HTML of an element inside the line code every three elements?
My complications start when I need to separate the opening tags ( <div class='row'>
) with the closing tag ( </div>
) and put the element codes (div columns) inside.
Let's assume there are a large number of items to iterate over.
The html results should look something like this if, for example, I have 7 elements:
<div class='row'>
<div class='column large-4'>item 1</div>
<div class='column large-4'>item 2</div>
<div class='column large-4'>item 3</div>
</div>
<div class='row'>
<div class='column large-4'>item 4</div>
<div class='column large-4'>item 5</div>
<div class='column large-4'>item 6</div>
</div>
<div class='row'>
<div class='column large-4'>item 7</div>
</div>
source to share
string BuildItems(int itemCount, int colsPerRow) {
StringBuilder sbItemHTML = new StringBuilder();
bool divBegin = true, divClosed = false;
for ( int i = 0; i < itemCount; i++ ) {
if ( divBegin ) {
sbItemHTML.AppendLine("<div class='row'>");
divBegin = false;
divClosed = false;
}
sbItemHTML.AppendLine("<div class='column large-4'>item " + i + "</div>");
if ( (i % colsPerRow == 0) && i > 0 ) {
sbItemHTML.AppendLine("</div>");
divBegin = true;
divClosed = true;
}
}
if ( !divClosed )
sbItemHTML.AppendLine("</div>");
return sbItemHTML.ToString();
}
how about trying this code?
Usage example: BuildItems (7, 3);
source to share
If you use a counter in a for loop; this will help you check by dividing the counter by 3 and check if the returned value is a full number. If so, add a closing div tag (and the next opening div tag). example below.
if (Math.Abs(i / 3) == (i / 3)) {
str = str + "<div class='column large-4'>" + value + "</div>" + "</div><div class='row'>";
}
else{
str = str + "<div class='column large-4'>" + value + "</div>";
}
source to share