Anchors are not generated

With the recipe Anchors and ToCs I have only partial success. ToCs are created correctly. Headlines have an ID. But what does not work is that headlines are converted as anchors.

I have tried it with the plugin - no change noticeable.
The field method did not work either.

What I did not understand in the recipe:

  • Are ALL headlines with a specified level converted into anchors?
  • I use 95% blocks/layouts. How do I have to adapt my template or snippet?

Not sure which part of the recipe you are trying out. There is a chapter about the blocks field right at the end: Anchors and ToCs | Kirby CMS

I have already tested all chapters several times without success.

I have just tested this steps:

  1. installed a fresh starter kit and created the plugin
    /site/plugins/toc/index.php

  2. /site/config/config.php
    extended it with levels 1-6:
    'k-cookbook.toc.headlines' => ['h2', 'h3', 'h4', 'h5', 'h6'],

  3. inserted a new headline in a notes article.

Result in the source code: No anchor :frowning:

Are any further steps required?
ToCs and IDs work.
It fails because of replacing the headlines with anchors :frowning:

The plugin refers to kirbytext, so it will only work with the kirbytext method.

However, to create anchors for headline blocks, you need to change the headline block snippet as explained in the part of the recipe I linked to above.

The plugin refers to kirbytext, so it will only work with the kirbytext method.

Ahhh… then of course I understand why nothing happens with blocks :slight_smile:

The last chapter is about creating ToCs. This works perfectly for me.
What I would like to achieve are clickable headlines, as in the Kirby documentation, to send links without the recipient having to scroll through the article. Or is that an entirely different function?

https://getkirby.com/docs/cookbook/navigation/table-of-contents#extra-toc-from-blocks-field

<h2 id="extra-toc-from-blocks-field">
<a href="#extra-toc-from-blocks-field">Extra: ToC from blocks field</a>
</h2>

My code looks like:

<h2 id="extra-toc-from-blocks-field">Extra: ToC from blocks field</h2>

Now I’ve figured it out: I only had to add the heading snippet:

/site/snippets/blocks/heading.php

<<?= $level = $block->level()->or('h2') ?> id="<?= Str::slug($block->text()) ?>"><a href="#<?= Str::slug($block->text()) ?>"><?= $block->text() ?></a></<?= $level ?>>

The cookbook tells me how to add the ID. But the addition of a link to the headline is missing. Is it intentional that this information is not mentioned in the cookbook?

Because the anchor is not necessary, is it? You link to the element specified by an id. It only needs to be an anchor if you want to be able to copy a link to it? The ToC itself works without the anchor.

1 Like

Thank you for the explanation and clarification. Now the topic is much easier for me to understand, and I have just been able to upgrade my website with the function. :pray: