caseyamcl/toc 问题修复 & 功能扩展

解决BUG、新增功能、兼容多环境部署,快速响应你的开发需求

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

caseyamcl/toc

Composer 安装命令:

composer require caseyamcl/toc

包简介

Simple Table-of-Contents Generator for PHP. Generates TOCs based off H1...H6 tags

README 文档

README

Generates a Table of Contents from H1...H6 Tags in HTML Content

Latest Version on Packagist Software License Github Build Code coverage PHPStan Level 8 Total Downloads

NOTE: Version 4 of this library requires PHP 8.2 or newer.

  • Version 3 is no longer maintained, but it supports PHP 7.2 - 8.1: composer require caseyamcl/toc ^3.0
  • Version 2 is no longer maintained, but it supports PHP5 - 7.1: composer require caseyamcl/toc ^2.0

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.

Features:

  • 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
  • Unit-tested (95% coverage) and PHPStan Level 7 tested

In the spirit of KISS philosophy, this library makes a few assumptions:

  1. The hierarchy of your content is defined solely by the header (H1...H6) tags. All other tags are ignored when generating the TOC.
  2. The link titles in the Table of Contents match either the title attribute of the header tag, or if there is no title, the (slugged) plaintext body of the header tag.

Installation Options

Install via Composer by including the following in your composer.json file:

composer require caseyamcl/toc ^4.0

Or, drop the src folder into your application and use a PSR-4 autoloader to include the files.

Usage

This package contains two main classes:

  1. 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)
  2. TOC\TocGenerator: Generates a Table of Contents from HTML markup

Basic Example:

$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  = "<div class='content'>" . $markupFixer->fix($myHtmlContent) . "</div>";

// This generates the Table of Contents in HTML
$htmlOut .= "<div class='toc'>" . $tocGenerator->getHtmlMenu($htmlOut) . "</div>";

echo $htmlOut;

This produces the following output:

<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.

To enable Twig integration, register the TocTwigExtension with your Twig environment:

use Twig\Environment;
use Twig\Loader\FilesystemLoader;

$myTwig = new Environment(new FilesystemLoader());
$myTwig->addExtension(new TOC\TocTwigExtension());

The extension adds a Twig function for generating an HTML Table of Contents:

{# 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:

{# Adds anchor links (id tags) for given htmlContent #}
{{ add_anchors(htmlContent) }}

{# You can also use it as a filter #}
<div class='my_content'>
    {{ htmlContent | add_anchors }}
</div>

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.

For example:

{% extends 'base.html.twig' %}
{% block page_content %}
<div class='page_sidebar'>
   {{ toc(add_anchors(block('my_writeup'))) }}
</div>

<div class='page_content'>
   {{ add_anchors(block('my_writeup')) }}
</div>
{% endblock %}

{% block my_writeup %}
<h1>Hi There</h1>
<p>Lorum ipsum baz biz etecetra</p>
<h2>This is some content</h2>
<p>More content here.  Blah blah</p>
{% 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:

$tocGenerator = new TOC\TocGenerator();
$someHtmlContent = '<div><h1>Test</h1><p>Lorum ipsum</p><h2>Test2</h2><p>Lorum ipsum</p></div>';

// 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:

$tocGenerator = new TOC\TocGenerator();
$markupFixer = new TOC\MarkupFixer();
$someHtmlContent = '<div><h1>Test</h1><p>Lorum ipsum</p><h2>Test2</h2><p>Lorum ipsum</p></div>';


// 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:

{# Generate TOC using h2, h3 tags #}
{{ toc(my_content, 2, 3) }}

{# Add anchors to h4, h5, h6 tags #}
{{ my_content | add_anchors(4, 3) }}

Customizing Menu Output

You can customize the rendering of lists that the TocGenerator class outputs. By default, TocGenerator uses the KnpMenu ListRenderer class to output the HTML.

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).

For example, you may wish to use different CSS classes for your list items:

$someHtmlContent = '<div><h1>Test</h1><p>Lorum ipsum</p><h2>Test2</h2><p>Lorum ipsum</p></div>';

$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:

use Knp\Menu\Matcher\Matcher;
use Knp\Menu\Renderer\TwigRenderer;
use Twig\Environment;
use Twig\Loader\FilesystemLoader;

$someHtmlContent = '<div><h1>Test</h1><p>Lorum ipsum</p><h2>Test2</h2><p>Lorum ipsum</p></div>';

$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 includes a custom renderer for ordered lists:

$someHtmlContent = '<div><h1>Test</h1><p>Lorum ipsum</p><h2>Test2</h2><p>Lorum ipsum</p></div>';

// Ordered List
$orderedRenderedList = (new TOC\TocGenerator())->getOrderedHtmlMenu($someHtmlContent);

Twig Usage:

{# Generate ordered TOC #}
{{ toc_ordered(my_content) }}

{# The same options can be used for ordered lists as unordered lists #}
{{ toc_ordered(my_content, 1, 3) }}

Making ordered lists prettier using CSS

Below is some CSS to make your ordered lists look extra fancy (credit to @flaushi).

.toc ol {
  list-style-type: none;
  counter-reset: item;
  margin: 0;
  padding: 0;
}

.toc ol > li:before  {
  counter-increment: item;
  margin: 0;
  padding: 0;
  content: counters(item, ".") ". ";

Sample output:

1. Some heading
1.1 Some sub-heading
1.2 Another sub-heading
2. Another heading
2.0.1. Sub-sub-sub heading

caseyamcl/toc 适用场景与选型建议

caseyamcl/toc 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 371.69k 次下载、GitHub Stars 达 89, 最近一次更新时间为 2015 年 01 月 23 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「TOC」 「table of contents」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 caseyamcl/toc 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 caseyamcl/toc 我们能提供哪些服务?
定制开发 / 二次开发

基于 caseyamcl/toc 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 371.69k
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 91
  • 点击次数: 29
  • 依赖项目数: 6
  • 推荐数: 0

GitHub 信息

  • Stars: 89
  • Watchers: 1
  • Forks: 15
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2015-01-23