Update (post): only show table of contents if there are at least 3 toc items

This commit is contained in:
2023-09-25 19:54:51 +08:00
parent 8faf131f13
commit e3fe8bf877
8 changed files with 82 additions and 94 deletions

View File

@@ -141,9 +141,16 @@ private function injectTableOfContents($html)
{
$crawler = new Crawler($html);
$h2Elements = $crawler->filter('h2');
if ($h2Elements->count() < 3) {
// Return the original HTML if there are fewer than 3 h2 tags
return $html;
}
// Create the Table of Contents
$toc = '<div class="p-3 rounded-3 bg-light mb-3"><ol>';
$crawler->filter('h2')->each(function (Crawler $node, $i) use (&$toc) {
$h2Elements->each(function (Crawler $node, $i) use (&$toc) {
$content = $node->text();
$id = 'link-'.$i; // Creating a simple id based on the index
$node->getNode(0)->setAttribute('id', $id); // Set the id to the h2 tag
@@ -162,7 +169,6 @@ private function injectTableOfContents($html)
$updatedHtml = $crawler->filter('body')->html();
return $updatedHtml;
}
private function injectFeaturedImage($post, $content)