We use cookies to ensure that we give you the best experience on our website. We also use cookies to ensure we show you advertising that is relevant to you.If you continue without changing your browser settings, we will assume that you are happy to receive all cookies on this website.

Table of contents

Generate a table of contents for your pages based on the heading tags. It requires, depending on how you want to use it, IDs or anchors in your page.

This article originates from the former CMSMS Wiki, the original authors are Elijah Lofgren and Simon Schaufelberger.

User Defined Tag, named "table_of_contents"

/** * Generates a table of contents based on parameters you want * @example: <h2 id="packages">Packages</h2> use: tag="h2" type="id" * @example: <a name="packages">Packages</a> use: tag="a" type="name" */function get_table_of_contents($page_contents,$tag,$type){preg_match_all("/<$tag$type=\"([a-z-0-9]+)\">(.*)<\/$tag>/i",$page_contents,$match);if(false==empty($match[0])){$contents="<ul>\n";foreach($match[1]as$key=>$value){if($type==$match[1][$key]){$contents.='';}else{$contents.=' ';}$contents.='<li><a href="'.$_SERVER['REQUEST_URI'].'#'.$match[1][$key].'">'.$match[2][$key].'</a>';// Start a new sub-list if this item has children otherwise just end the list itemif(false==empty($match[1][$key+1])&&$match[1][$key+1]==$match[1][$key]+1){$contents.="\n <ul>\n";$unclosed_list=TRUE;}else{$contents.="</li>\n";}// If the next item is higher level then close this list item // In example current item is h3 and next is h2if(false==empty($match[1][$key+1])&&$match[1][$key+1]==$match[1][$key]-1){$contents.=" </ul>\n</li>\n";$unclosed_list=FALSE;}}if(false==empty($unclosed_list)){$contents.=" </ul>\n</li>\n";}$contents.="</ul>\n";}else{$contents='';}return$contents;}

2 Comments

Very nice - exactly what I am looking for. The only difficulty is: how to get it into the template? I use the standard "Left simple navigation + 1 column" and it complains about "duplicate content_en block". Any idea about this?