Hello,
Can I use a snippet to create a reusable block of code that I can use to dynamically insert the title into a link in a blog post?
I would like to output the link text “Comment via eMail” and a mailto link that looks like this:
mailto:me@web.com?subject=Blog%20articel&body=Some%20text
The subject should then be replaced by the title of the respective article.
Thank you for your tricks.
Oziris
January 3, 2025, 12:53pm
2
You could create a new file called email-link.php
in your site/snippets
folder.
site/snippets/email-link.php
:
<?php
$title = urlencode($page->title());
$email = 'me@web.com';
echo '<a href="mailto:' . $email . '?subject=' . $title . '&body=Some%20text">Comment via eMail</a>';
?>
In your blog template or markdown file where you want the email link to appear, insert the snippet like this:
<?php snippet('email-link') ?>
1 Like
Hey Oziris,
thank you very much for the answer. That looks good!
The editor uses blocks and has no HTML element. When I use
<?php snippet('email-link') ?>
as markdown, the code just outputs and doesn’t execute.
What can I do there?
Oziris
January 3, 2025, 1:11pm
4
If you’re using Kirby’s blocks field, you can insert the snippet directly into a blog post with:
{{ snippet('email-link') }}
However, this is not done with a normal text block element:
M_G
January 8, 2025, 8:05am
6
What happen if you change your code to
site/snippets/email-link.php
<?php
$title = urlencode($page->title());
$email = 'me@web.com';
$html = '<a href="mailto:' . $email . '?subject=' . $title . '&body=Some%20text">Comment via eMail</a>';
echo htmlspecialchars($html);
?>
and use
<?php snippet('email-link') ?>
Hi,
If you want to use it inside of markdown you should create a own kirbytag.
If I understand correctly, you want to add a placeholder, that you can later replace with the mailto link, right?
In which block type is this placeholder supposed to be used?
You could add a placeholder like this {{comment.link}}
wherever you want this link to appear.
Then in any block snippets where you can expect this placeholder, replace it.
Let’s take the text block snippet as example. So the overwritten text block snippet, which by default looks like this:
<?php /** @var \Kirby\Cms\Block $block */ ?>
<?= $block->text();
Would be replaced with
<?php /** @var \Kirby\Cms\Block $block */ ?>
<?= Str::template($block->text(), [
'comment.link' => '<a href="mailto:me@web.com?subject=' . $block->parent()->title() . '&body=Some%20text">Comment via eMail</a>',
]);
See also: Placeholders | Kirby CMS
This approach also works for markdown fields without any kirbytags.