Created
June 15, 2023 09:19
-
-
Save lukaskleinschmidt/dd2ded975c79af749f94600d1a24bb45 to your computer and use it in GitHub Desktop.
Kirby Snippet Assets Plugin using Vite
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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