Using ColdFusion Loops with Bootstrap Rows and Columns
One of the most common application requirements is outputting an arbitrary amount of data in organized rows and columns. It used to be done with tables, now it’s done with Bootstrap; it looks better, but the principle is the same: output items until the row is full, then start a new one - and make sure you close all the tags that you open, in the correct order.
I’ve handled this in a variety of ways in the past; sometimes with a variety of incrementing counters and
<cfif> tags, occasionally with
<cfoutput group="someCol">. It always ended up cluttering the view and it never felt clean. While every situation is different, I recently hit upon a simple solution for outputting data in Bootstrap’s rows and columns, using ColdFusion’s ternary and mod operators (of course those links are to Ben Nadel’s blog).
Here was the situation: I needed to output data in four columns, with as many rows as necessary. Rather than beating around the bush, here’s the code:
#(loopIndex MOD 4 EQ 1) ? '' : ''#' : ''#
#(loopIndex MOD 4 EQ 0 OR loopIndex EQ arrayOfData.len()) ? '
Just a few notes on it:
- We’re using ColdFusion 11, so it uses the very convenient
array.len()syntax, instead of
- We’re outputting 4 items per row, which is why it’s
MOD 4, and why Bootstrap’s 12 grid columns are broken down into
- You’ll see that the logic of the opening and closing
modoperations are based on 1 and 0, respectively, based on whether it should be the opening or closing of the row div.
- Additionally, the closing
modalso needs to account for closing the row if it is the last item in the array.
So, nothing groundbreaking here, but I was pleased with how clean the resulting code was. I’m sure there are circumstances that will require additional logic and manipulation, but this served my purpose - and I think it would provide the basis of my approach for more complex situations.