4 * Implementation of hook_theme().
6 function toc_formatter_theme() {
8 'toc_formatter_table_of_contents' => array(
9 'variables' => array('content' => NULL, 'title' => NULL, 'type' => 'ul'),
11 'toc_formatter_move_to_top_link' => array(
12 'variables' => array('content' => NULL),
21 * Theming functions for 'Move to top' links.
23 function theme_toc_formatter_move_to_top_link($variables) {
24 $content = $variables['content'];
25 $path_alias = request_uri();
26 $link = '<div class="toc-top-links">';
27 $link .= l(t('Move to top'), $path_alias, array('fragment' => 'table-of-contents'));
30 $output = str_ireplace('</h2>', '</h2>'. $link, $content);
35 * Generate table of contents, add anchors to headings, and add links back to top of page.
38 function theme_toc_formatter_table_of_contents($variables) {
40 $title = $variables['title'];
41 $content = $variables['content'];
42 $type = $variables['type'];
44 $path = request_uri();
49 $dom_document = new DOMDocument('1.0','utf-8');
50 @$dom_document->loadHTML('<?xml encoding="UTF-8"><div id="toc-formatter">'. $content .'</div>');
52 $headers = $dom_document->getElementsByTagName('h2');
54 foreach ($headers as $header) {
58 $label = trim($header->nodeValue);
59 $links[] = l($label, $path, array('fragment' => 'toc-'. $anchor));
61 // Headings, add class.
62 $header->setAttribute('class', 'toc-headings');
64 // Anchors above headings.
65 $anchor_div = $dom_document->createElement('div');
66 $anchor_div->setAttribute('class', 'toc-item-anchor');
67 $target = $dom_document->createElement('a');
68 $target->setAttribute('name', 'toc-'. $anchor);
69 $anchor_div->appendChild($target);
70 $header->parentNode->insertBefore($anchor_div, $header);
73 if (isset($links) && !empty($links)) {
74 // Output DOM to a string.
75 // Unfortunately below PHP 5.3.6 saveHTML() doesn't expect a parameter.
76 $content_updated = $dom_document->saveHTML();
77 // So we have to remove wrapping tags ourseleves.
78 $content_fragments = explode('<div id="toc-formatter">', $content_updated);
79 $content_inner = str_replace('</div></body></html>', '', $content_fragments[1]);
81 $output .= '<div id="table-of-contents-links">';
82 $output .= '<a name="table-of-contents"></a>';
83 $item_list = array('#theme' => 'item_list', '#items' => $links, '#title' => $title, '#type' =>$type);
84 $output .= drupal_render($item_list);
88 $top_link = array('#theme' => 'toc_formatter_move_to_top_link', '#content' => $content_inner);
89 $output .= drupal_render($top_link);