Skip to content

Instantly share code, notes, and snippets.

@lukaskleinschmidt
Created June 15, 2023 09:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lukaskleinschmidt/dd2ded975c79af749f94600d1a24bb45 to your computer and use it in GitHub Desktop.
Save lukaskleinschmidt/dd2ded975c79af749f94600d1a24bb45 to your computer and use it in GitHub Desktop.
Kirby Snippet Assets Plugin using Vite
<?php
use Kirby\Cms\App;
use Kirby\Toolkit\A;
App::plugin('lukaskleinschmidt/snippet-assets', [
'hooks' => [
'page.render:after' => function (string $contentType, string $html) {
if ($contentType === 'html') {
$html = preg_replace_callback('/<\/head>/', fn ($matches) =>
SnippetAssets::assets() . $matches[0]
, $html);
}
return $html;
},
],
'components' => [
'snippet' => function (App $kirby, $name, array $data = [], bool $slots = false) {
SnippetAssets::for($name);
return $kirby->core()->components()['snippet'](
$kirby,
$name,
$data,
$slots,
);
}
],
]);
class SnippetAssets
{
/**
* The snippet assets.
*/
public static $assets = [];
/**
* Add a snippet script.
*/
public static function assets(): string
{
$assets = [];
foreach (static::$assets as $name) {
$assets[] = "@assets/js/snippets/{$name}.js";
$assets[] = "@assets/css/snippets/{$name}.css";
}
return vite($assets);
}
/**
* Resolve snippet assets.
*/
public static function for(string|array $name): void
{
if ($name = static::name($name)) {
static::$assets[$name] = $name;
}
}
/**
* Get the snippet name.
*/
public static function name(string|array $name): ?string
{
$kirby = App::instance();
$names = A::wrap($name);
$root = $kirby->root('snippets');
foreach ($names as $name) {
$file = $root . '/' . $name . '.php';
if (file_exists($file) === false) {
$file = $kirby->extensions('snippets')[$name] ?? null;
}
if ($file) {
return $name;
}
}
return null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment