Sorry, this page is only available in one language

CreateToc

Suggested dropletname: CreateToc

Published by: WebBird

Creates a Table of Contents from Headings (h1 - h6)

$toc     = array();
$output  = NULL;
$number  = ( isset($number) ? true : false );
$current = array( '1' => 0 );
$last    = 1;
$dump    = array();
$strings = array(
  'DE' => 'Auf dieser Seite...',
  'EN' => 'On this page...',
);
preg_match_all( '#<h([1-6]).*>([^<].+)</h[1-6]>#i', $wb_page_data, $matches, PREG_PATTERN_ORDER );
if ( count($matches) ) {
    foreach( $matches[2] as $i => $text ) {
        $level = $matches[1][$i]; // current level
        if ( $number ) {
            if ( $level < $last ) {
                for( $n=($level+1); $n<=$last; $n++ ) {
                    unset($current[$n]);
                }
            }
            if ( isset( $current[$level] ) ) {
                $current[$level]++;
            }
            else {
                $current[$level]=1;
            }
            $prefix = array();
            for( $m=1; $m<=$level; $m++ ) {
                if ( ! isset($current[$m] ) ) {
                    $current[$m] = 1;
                }
                $prefix[] = $current[$m];
            }
            $text = implode('.', $prefix ) . ' ' . $text;
        }
        $last  = $level;
        $toc[] = '<span style="margin-left:'
               . ( 10 * ( $level - 1 ) )
               . 'px;"><a href="#toc'.$i.'">'.$text.'</a></span>';
        $wb_page_data = str_replace(
            $matches[0][$i],         
            ( ( $i > 0 ) ? '<br /><a href="#toc">Back to top</a><br />' : '' ).
            '<a name="toc'.$i.'">Â </a>' . $matches[0][$i],
            $wb_page_data
        );
    }
    $output = '<div class="toc" style="margin:5px;padding:5px;border:1px solid #ccc;';
    if ( isset($float) && $float == 'right' ) {
        $output .= ' float:right;';
    }
    $output .= '">'
            . '<a name="toc" style="font-weight:bold;">'
            . ( isset($strings[LANGUAGE]) ? $strings[LANGUAGE] : $strings['EN'] )
            . '</a><br /><br />'
            .  implode( '<br />', $toc )
            .  '</div>';
}
return $output;

Create a Table of Contents by extracting all headings from a page

Usage: (parameters are optional)

[[CreateToc?float=right&number=1]]


[[CreateToc?float=right]]  -> Let the Toc float right
[[CreateToc?number=1]] -> Number the menu entries


You can style the Toc by CSS class "toc".

Please note: If your template contains "hardcoded" headings, they will appear in the Toc, too. So you may have to replace hardcoded headings with some other markup.



| Overview | Next droplet »