How to create simple methods to render snippets

If you work with Kirby a lot, you probably have some snippets you use all the time. Not a big deal in itself, but the default snippet syntax can get pretty verbose over time, especially when you use the same snippet in many places.

Let's see how a simple helper method can make your snippet calls much shorter and more readable.

Default snippet syntax

In my projects, I often use an icon snippet that renders an SVG from a sprite. It accepts two parameters, $name and $size, and looks like this:

<?php
use Kirby\Toolkit\Str;

$name = $name ?? "";
$size = $size ?? "1em";
$sprite = asset('icons.svg');
?>

<i class="i" style="--size: <?= $size ?>" data-icon="<?= $name ?>">
  <svg aria-hidden>
    <use xlink:href="<?= $sprite->url() ?>?v=<?= $sprite->mediaHash() ?>#symbol-<?= $name ?>" />
  </svg>
</i>

Normally, you'd call the snippet like this:

<?php snippet('icon', ['name' => 'phone', 'size' => '1.25em']);?>

Works perfectly fine, but let's be honest, for a tiny icon inside a simple HTML structure, that's a bit cumbersome. Wouldn't it be nice to write it like this?

<?= icon('phone') ?>

The solution: A small plugin

Here is how you do it:

  1. Create a new folder in site/plugins and name it something like project-helper. I like differentiating internal plugins from externally installed ones by name, but you can call the folder whatever you want of course.
  2. In the plugin's index.php, add the new method:
function icon(string $name, string $size = '1em') {
	return snippet('icon', ['name' => $name, 'size' => $size], true);
}

The method is basically just a slim wrapper around Kirby's snippet() method. It accepts the same parameters and returns the rendered snippet. The key detail: Passing true as the third argument makes the snippet return the HTML as a string instead of echoing it directly.

This principle applies to any snippet you use frequently of course. Especially for small, recurring building blocks like icons, buttons, or badges, it saves quite a bit of typing and makes your templates noticeably cleaner.