Filed under Concrete5

Creating a Table of Contents in Concrete5

I recently had a requirement where I needed to create an article template for a site running on Concrete5. The articles needed to have a table of contents displayed in a box next to the article. Further, I wanted to come up with a solution that didn’t rely on JavaScript. I did what I normally do and turned to my good friend Google to see what other people had done.

The first part, creating a table of contents in PHP, turned out to be pretty simple.  I found a question on StackOverflow that was pretty close to what I needed. The code needed a good bit of tweaking to get working, but I was able to create something that at least got the job done. However, not only did I need to feed it the contents of the block/area I wanted a table of contents for, I also needed to modify the contents to have anchor tags for quick navigation.

This part proved to be a little more difficult. I had hoped that Concrete5 had a block or area function that would output the HTML into a variable for me. Unfortunately, there is no such method. Fortunately, while Googling an answer I came across a post about getting the contents of a block. I had completely forgotten about PHP’s functions for capturing output. I could use ob_start() and ob_get_clean() to capture the results of an Area’s display() function:

$a = new Area('Main');
$html = ob_get_clean();

I could then take the results and pass them to my table of contents function. In the function, I modified the passed-in HTML then displayed it and also returned the table of contents so I could place it into a variable to display later in my template.

I’m certain it could be a lot cleaner, and, if I get motivated, I may turn it into a real-live block that can be dropped onto a page.