Group MODX Resources into Columns

The Need

getResources is the all-in-one swiss-army-knife of MODX Snippets. You can do alot with it, from galleries to menus to paginated things like blogs. Used in an optimized way—and with a bit of MODX magic sprinkled in—it’ll even scale for massively busy sites that serve huge amounts of traffic. Here’s just one example.

There is thing one little thing, though, that occasionally I need to do, and getResources doesn’t handle it very well: columns. Or more accurately—grouping.

Take this for example:

<ol>
<li>First item</li>
<li>Second item</li>
<li>Third item</li>
<li>Fourth item</li>
<li>Fifth item</li>
<li>Sixth item</li>
<li>Last item</li>
</ol>

The number of items is arbitrary. getResources allows you to format the output of each item, by it’s position in the list, like: first, last, nth position or nNth position (every 4th, for example). You can even apply conditional formatting based on some attribute of the Resource, like whether it’s a weblink or document, or which Template it uses. Really powerful stuff. However, what if your desired markup looks more like this:

<ol class="first column">
<li>First item</li>
<li>Fourth item</li>
<li>Last item</li>
</ol>
<ol class="second column">
<li>Second item</li>
<li>Fifth item</li>
</ol>
<ol class="third column">
<li>Third item</li>
<li>Sixth item</li>
</ol>

Note that the first three items aren’t grouped together in the first column—that would be easy. The items have be pre-sorted into consecutive groups, in the order they’re returned. getResources doesn’t do this. I’ve done a workaround where you call getResources multiple times, passing it offset and limit properties based on some calculations off the total results, etc etc. Let me tell you it’s not pretty.

getResourcesColumns

Enter a new Snippet, getResourcesColumns. It’s not an Extra yet. It will probably be, sometime soon, but until then you can copy and paste the gist (embedded below) into a Snippet in your MODX site and use it similarly to getResources. It doesn’t have the same conditional formatting as getResources—only &rowTpl and &colWrapTpl, but for those times when you need columns, it’s handy. Check out the code comments for documentation, and if you have any thoughts on it (especially a better way to get TVs when they’re needed) please post in Disqus below :)