PHP TOC Generator
Generates a Table of Contents from H1...H6 Tags in HTML Content, (*1)
[][link-ghbuild]
, (*2)
NOTE: This library now requires PHP 7.2 or newer; to retain PHP5-7.1 support, use the following composer directive:
composer require caseyamcl/toc ~2.0.0
, (*3)
This package provides a simple, framework-agnostic library to build
a Table-of-Contents from HTML markup. It does so by evaluating your H1...H6 tags.
It can also automatically add appropriate id anchor attributes to header tags so that in-page links work., (*4)
Features:, (*5)
- Generates HTML menus and KnpMenu Item Menus
- Adds anchor ID attributes to H1...H6 tags in your content where they do not already exist
- You can specify which H1...H6 heading tag levels to include in the TOC
- Includes a Twig Extension for generating TOCs and compatible markup directly in your templates
- Uses the flexible KnpMenu Library to generate menus
-
PSR-12 compliant
- Composer-compatible
- Unit-tested (95% coverage)
In the spirit of KISS philosophy, this library makes a few assumptions:, (*6)
- The hierarchy of your content is defined solely by the header (H1...H6) tags. All other tags are ignored when generating the TOC.
- The link titles in the Table of Contents match either the
title
attribute of the header tag, or if there is no title
, the (slugified) plaintext body of the header tag.
Installation Options
Install via Composer by including the following in your composer.json
file:, (*7)
{
"require": {
"caseyamcl/toc": "^3.0",
}
}
Or, drop the src
folder into your application and use a PSR-4 autoloader to include the files., (*8)
Usage
This package contains two main classes:, (*9)
-
TOC\MarkupFixer
: Adds id
anchor attributes to any H1...H6 tags that do not already have any (you can specify which header tag levels to use at runtime)
-
TOC\TocGenerator
: Generates a Table of Contents from HTML markup
Basic Example:, (*10)
$myHtmlContent = <<<END
<h1>This is a header tag with no anchor id</h1>
<p>Lorum ipsum doler sit amet</p>
<h2 id='foo'>This is a header tag with an anchor id</h2>
<p>Stuff here</p>
<h3 id='bar'>This is a header tag with an anchor id</h3>
END;
$markupFixer = new TOC\MarkupFixer();
$tocGenerator = new TOC\TocGenerator();
// This ensures that all header tags have `id` attributes so they can be used as anchor links
$htmlOut = "
" . $markupFixer->fix($myHtmlContent) . "
";
// This generates the Table of Contents in HTML
$htmlOut .= "
" . $tocGenerator->getHtmlMenu($htmlOut) . "
";
echo $htmlOut;
This produces the following output:, (*11)
<div class='content'>
<h1 id="this-is-a-header-tag-with-no-anchor-id">This is a header tag with no anchor id</h1>
<p>Lorum ipsum doler sit amet</p>
<h2 id="foo">This is a header tag with an anchor id</h2>
<p>Stuff here</p>
<h3 id="bar">This is a header tag with an anchor id</h3>
</div>
<div class='toc'>
<ul>
<li class="first last">
<span></span>
<ul class="menu_level_1">
<li class="first last">
<a href="#foo">This is a header tag with an anchor id</a>
<ul class="menu_level_2">
<li class="first last">
<a href="#bar">This is a header tag with an anchor id</a>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
Twig Integration
This library includes a Twig extension that
enables you to load TOC lists and add anchors to markup from your Twig templates., (*12)
In order to enable Twig integration, you must register the
TocTwigExtension
with your Twig environment:, (*13)
use Twig\Environment;
use Twig\Loader\FilesystemLoader;
$myTwig = new Environment(new FilesystemLoader());
$myTwig->addExtension(new TOC\TocTwigExtension());
Specifically, the extension adds a Twig function for generating Table of Contents HTML:, (*14)
{# Generates HTML markup for given htmlContent #}
<ul>{{ toc(htmlContent) }}</ul>
It also provides a function and a filter for ensuring that your content
includes anchors for all HTML header tags. They both do the same thing,
so choose which one suits your needs best:, (*15)
{# Adds anchor links (id tags) for given htmlContent #}
{{ add_anchors(htmlContent) }}
{# You can also use it as a filter #}
{{ htmlContent | add_anchors }}
Your HTML content may be hard-coded in your Twig Template. An easy way
to accommodate this is to make sure the content is surrounded by
{% block %}...{% endblock %}
tags, and then just pass in that block to the toc function., (*16)
For example:, (*17)
{% extends 'base.html.twig' %}
{% block page_content %}
{{ add_anchors(block('my_writeup')) }}
{% endblock %}
{% block my_writeup %}
Hi There
Lorum ipsum baz biz etecetra, (*18)
This is some content
More content here. Blah blah, (*19)
{% endblock %}
Specifying Heading Levels to Include
You can choose to include only specific h1...h6 heading levels in your TOC.
To do this, pass two additional arguments to the
TocGenerator::getHtmlMenu()
method: $topLevel
and $depth
. For example:, (*20)
$tocGenerator = new TOC\TocGenerator();
$someHtmlContent = '
Test
Lorum ipsum, (*21)
Test2
Lorum ipsum, (*22)
';
// Get TOC using h2, h3, h4
$tocGenerator->getHtmlMenu($someHtmlContent, 2, 3);
// Get TOC using h1, h2
$tocGenerator->getHtmlMenu($someHtmlContent, 1, 2);
// Get TOC using h4, h5, h6
$tocGenerator->getHtmlMenu($someHtmlContent, 4, 3);
Most other methods in the package handle these arguments as well:, (*23)
$tocGenerator = new TOC\TocGenerator();
$markupFixer = new TOC\MarkupFixer();
$someHtmlContent = '
Test
Lorum ipsum, (*24)
Test2
Lorum ipsum, (*25)
';
// Get KnpMenu using h1, h2, h3
$tocGenerator->getMenu($someHtmlContent, 1, 3);
// Fix markup for h3, h4 tags only
$markupFixer->fix($someHtmlContent, 3, 2);
Twig functions and filters accept these arguments as well:, (*26)
{# Generate TOC using h2, h3 tags #}
{{ toc(my_content, 2, 3) }}
{# Add anchors to h4, h5, h6 tags #}
{{ my_content | add_anchors(4, 3) }}
You can customize the rendering of lists that the TocGenerator
class
outputs. By default, TocGenerator
uses the KnpMenu ListRenderer
class to output the HTML., (*27)
You can pass your own instance of the ListRenderer
class to
TocGenerator::getHtmlMenu()
. Or, you can pass in your own renderer
(implements Knp\Menu\Renderer\RendererInterface
)., (*28)
For example, you may wish to use different CSS classes for your list items:, (*29)
$someHtmlContent = '
Test
Lorum ipsum, (*30)
Test2
Lorum ipsum, (*31)
';
$options = [
'currentAsLink' => false,
'currentClass' => 'curr_page',
'ancestorClass' => 'curr_ancestor',
'branch_class' => 'branch'
];
$renderer = new Knp\Menu\Renderer\ListRenderer(new Knp\Menu\Matcher\Matcher(), $options);
// Render the list
$tocGenerator = new TOC\TocGenerator();
$listHtml = $tocGenerator->getHtmlMenu($someHtmlContent, 1, 6, $renderer);
Customizing with Twig
The KnpMenu library offers more robust integration with the Twig Templating System
than is offered by default with this library. You can take advantage of it by using the TwigRenderer
that is bundled with KnpMenu:, (*32)
use Knp\Menu\Matcher\Matcher;
use Knp\Menu\Renderer\TwigRenderer;
use Twig\Environment;
use Twig\Loader\FilesystemLoader;
$someHtmlContent = '
Test
Lorum ipsum, (*33)
Test2
Lorum ipsum, (*34)
';
$twigLoader = new FilesystemLoader(array(
__DIR__.'/vendor/KnpMenu/src/Knp/Menu/Resources/views',
// ...paths to your own Twig templates that render KnpMenus...
));
$twig = new Environment($twigLoader);
$itemMatcher = new Matcher();
$menuRenderer = new TwigRenderer($twig, 'knp_menu.html.twig', $itemMatcher);
$tocGenerator = new TOC\TocGenerator();
// Output the Menu using the template
echo $menuRenderer->render($tocGenerator->getMenu($someHtmlContent));
Ordered vs Unordered Lists
The KnpMenu library produces unordered lists (ul
) by default. This
library contains a custom renderer for ordered lists, whether you're using
Twig or not:, (*35)
$someHtmlContent = '
Test
Lorum ipsum, (*36)
Test2
Lorum ipsum, (*37)
';
// Ordered List
$orderedRenderedList = (new TOC\TocGenerator())->getOrderedHtmlMenu($someHtmlContent);
Twig Usage:, (*38)
{# Generate ordered TOC #}
{{ toc_ordered(my_content) }}
{# The same options can be used for ordered lists as unordered lists #}
{{ toc_ordered(my_content, 2, 3) }}