Mark_E
October 24, 2024, 11:25am
1
We’re using the Writer field in the Panel. Is it possible to select some text and add an anchor ID to it – and then on the same page link to it?
The toolbar has an ‘Anchor’ option for adding an anchor. Should the first character be “#” or is this not needed? But then how do we link to it?
Hey Mark,
In the Writer field you can add an anchor link, which would need to look something like this #element
. This would refer to the id of an element on the page, e.g.
<div id="element">
The link would take you to me
</div>
You can’t set an id within the Writer field as far as I am aware. You could perhaps do something custom for this? See Writer marks/nodes | Kirby CMS .
The way I have handled this before is when using blocks, have a slug field in there for editors to add an id if they want to link to it: Slug | Kirby CMS
Mark_E
October 24, 2024, 2:29pm
3
Hi Mike,
Thanks, I’ll give it some thought… I was hoping there would be an out of the box way to do it
Perhaps Kirby 5 will include this?
Mark_E
November 8, 2024, 4:41pm
4
Hmm, so Kirby provides the option, in the Writer field to link to an anchor, but doesn’t provide the ability to create an anchor. Seems odd?
@Mark_E Create or extend the text.php snippet with a function to automatically convert a newly defined placeholder into an anchor target.
site/snippets/blocks/text.php
<?php
/** @var \Kirby\Cms\Block $block */
if (!function_exists('replaceAnchorTargets')) {
function replaceAnchorTargets($text) {
return preg_replace_callback('/\[anchor id="([^"]+)"\](.*?)\[\/anchor\]/', function($matches) {
$targetId = htmlspecialchars($matches[1], ENT_QUOTES, 'UTF-8');
$linkText = htmlspecialchars($matches[2], ENT_QUOTES, 'UTF-8');
return '<span id="' . $targetId . '">' . $linkText . '</span>';
}, $text);
}
}
$text = replaceAnchorTargets($block->text());
?>
<?= $text ?>
Use the following pattern in your writer-field to create an anchor target:
This is the [anchor id=“target-id”]target anchor[/anchor]
that the link should jump to.
Of course, it is important that the target ID matches the previously created anchor link ID # .
You can replace the <span>
element with another HTML element if desired.
Mark_E
November 18, 2024, 11:44am
6
I’ve created text.php snippet in site/snippets/blocks/
But in the Panel when I highlight text, I’m not seeing anything in the tool bar to wrap an ID around the text.
So I’ve then tried writing the following in the Panel:
[anchor id=“target-id”]target anchor[/anchor]
But this gets displayed in the front end in the browser.
Mark_E
November 18, 2024, 1:33pm
7
Thanks everyone for their help, but I’ve just found out we’re not going to use anchor links. Case closed for me.