PHP code example of alirezasedghi / laravel-toc

1. Go to this page and download the library: Download alirezasedghi/laravel-toc library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

alirezasedghi / laravel-toc example snippets


use Alirezasedghi\LaravelTOC\TOCGenerator;

class PageController extends Controller
{
    public function show(Request $request)
    {
        // Example HTML content
        $html = "<h1>Main Title</h1><h2>Section 1</h2><p>Content...</p>";

        // Initialize TOC generator
        $tocGenerator = new TOCGenerator($html);

        // Generate the TOC and get processed HTML
        $toc = $tocGenerator->generateTOC();
        $processedHtml = $tocGenerator->getProcessedHtml();

        // Return to view
        return view('page', [
            'toc' => $toc,
            'content' => $processedHtml
        ]);
    }
}

use Alirezasedghi\LaravelTOC\TOCGenerator;

class PageController extends Controller
{
    public function show(Request $request)
    {
        // Example HTML content
        $html = "<h1>Main Title</h1><h2>Section 1</h2><h3>Subsection</h3><p>Content...</p>";

        // Define custom options
        $options = [
            'list_type' => 'ol',             // Use an ordered list for the TOC
            'toc_class' => 'custom-toc',     // Class for TOC <ul>/<ol>
            'internal_list_class' => 'nested-toc', // Class for nested <ul>/<ol>
            'toc_item_class' => 'toc-item',  // Class for each <li>
            'toc_link_class' => 'toc-link',  // Class for each <a>
            'heading_class' => 'heading',    // Class for headings
            'min_level' => 2,                // Include only h2-h6
            'max_level' => 3                 // Include up to h3
        ];

        // Initialize TOC generator with custom options
        $tocGenerator = new TOCGenerator($html, $options);

        // Generate the TOC and get processed HTML
        $toc = $tocGenerator->generateTOC();
        $processedHtml = $tocGenerator->getProcessedHtml();

        // Return to view
        return view('page', [
            'toc' => $toc,
            'content' => $processedHtml
        ]);
    }
}