Skip to content

Is there a way to only return the TOC #718

Answered by colinodell
jonathanbriehl asked this question in Q&A
Discussion options

You must be logged in to vote

The Table of Contents is stored within a TableOfContents node in the AST. There are a few ways to accomplish what you're looking to do, but all of them will center around locating that node. Given a Document object named $document, you can grab the TOC with code like this:

$toc = (new Query())
    ->where(Query::type(TableOfContents::class))
    ->findOne($document);

if ($toc === null) {
    // No TOC is present
} else {
    // FOUND IT!
}

Or without using the fancy Query functionality:

function getTOC(Document $document): ?TableOfContents
{
    foreach ($document->iterator() as $node) {
        if ($node instanceof TableOfContents) {
            return $node;
        }
    }

    return n…

Replies: 2 comments

Comment options

You must be logged in to vote
0 replies
Answer selected by colinodell
Comment options

You must be logged in to vote
0 replies
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
3 participants