Matrix + Structure + Freebie = Expression Engine Image Gallery

One of the great things about ExpressionEngine as a CMS is the number of fantastic plugins there are.  Two that we really like are Matrix and Structure.  Matrix lets you attach an infinite number of records to an entry; think of it as an excel sheet where you can control where and how each column in a row appears on the front end.

Structure makes ExpressionEngine behave a little more like a traditional website and allows you to write URLs that make more sense for a non-blog website.  Structure does this by intercepting the URL and looking for a corresponding page.  A non-structure URL might look like:  http://mysite.com/pages/about  where pages is my template group and about is the template I want to display.  Structure lets us break that paradigm and use the more typical: http://mysite.com/about.  It takes care of knowing which template to display our data in.

Pixel and Tonic have a great tutorial on creating an Image Gallery with Matrix.  It’s intuitive for the end user and easy to style on the front-end.  Win-win.  Except when you get into their pagination example…

Let’s say you have a gallery of eight images and only want to display 4 at time.  We can accomplish this by adding a limit=”4″ to our opening matrix tag:  {mygallery limit=”4″} Add to this the “offset” parameter which says “skip the first x number of rows” and we can easily create pagination.

Pixel and Tonic use a new segment in the url to set the offset.  For instance in our example above the URL for the second page of images would look like:  http://mysite.com/gallery/4  This is where our problem happens.  Structure intercepts that “4″ and looks for a new page rather than passing it to the gallery page.  This is where Freebie comes in; Freebie lets us tell Structure to ignore any URL segments that are numerical. Note that you’ll have to change all {segment_x} tags to {freebie_x} tags.

The remaining problem is that when if users access our gallery at: http://mysite.com/gallery our pagination logic doesn’t see that as “0″ but rather “nil”  and since any number is always greater than nothing, we will get a “next” link where we may not want one.  Thankfully Freebie has a built in test to see if the URL segment is a number: {exp:freebie:is_number segment=”3″} From there it’s just a matter of writing some logic to handle non-numeric segments as “0″ rather than the expected value.

I hope that helps some of you who might be struggling to get a Matrix image gallery and Structure playing nicely.

Leave a Reply