Last active
June 15, 2023 08:36
-
-
Save lukaskleinschmidt/a8e9a76e6fce47430277553ca1332705 to your computer and use it in GitHub Desktop.
Kirby Snippet Assets Plugin
This file contains 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::styles() . SnippetAssets::scripts() . $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 styles. | |
*/ | |
public static $styles = []; | |
/** | |
* The snippet scripts. | |
*/ | |
public static $scripts = []; | |
/** | |
* Resolve snippet assets. | |
*/ | |
public static function for(string|array $name): void | |
{ | |
if ($name = static::name($name)) { | |
static::script($name); | |
static::style($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; | |
} | |
/** | |
* Add a snippet script. | |
*/ | |
public static function script(string $name): void | |
{ | |
if (isset(static::$scripts[$name])) { | |
return; | |
} | |
$script = asset('assets/snippets/' . $name . '.js'); | |
if ($script->exists()) { | |
static::$scripts[$name] = js($script); | |
} | |
} | |
/** | |
* Get all snippet scrtips. | |
*/ | |
public static function scripts(): string | |
{ | |
return implode(PHP_EOL, static::$scripts); | |
} | |
/** | |
* Add a snippet style. | |
*/ | |
public static function style(string $name): void | |
{ | |
if (isset(static::$styles[$name])) { | |
return; | |
} | |
$style = asset('assets/snippets/' . $name . '.css'); | |
if ($style->exists()) { | |
static::$styles[$name] = css($style); | |
} | |
} | |
/** | |
* Get all snippet styles. | |
*/ | |
public static function styles(): string | |
{ | |
return implode(PHP_EOL, static::$styles); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment