Skip to content

Instantly share code, notes, and snippets.

@ichik
Last active July 9, 2022 17:11
Show Gist options
  • Save ichik/3191c85570821170a86b581199f4a8ee to your computer and use it in GitHub Desktop.
Save ichik/3191c85570821170a86b581199f4a8ee to your computer and use it in GitHub Desktop.
<?php
/**
* Lazy
*
* This plugin makes automatic markup for images to display with lazySizes.js from markdown
* You need to set twig_first: true in pages: in system.yaml config for it to work properly
*
*/
namespace Grav\Plugin;
use Grav\Common\Grav;
use Grav\Common\Plugin;
use Grav\Common\Page\Page;
use RocketTheme\Toolbox\Event\Event;
class lazyPlugin extends Plugin
{
/**
* Return a list of subscribed events.
*
* @return array The list of events of the plugin of the form
* 'name' => ['method_name', priority].
*/
public static function getSubscribedEvents()
{
return [
'onPluginsInitialized' => ['onPluginsInitialized', 0],
'onTwigSiteVariables' => ['onTwigSiteVariables', 0]
];
}
/**
* Initialize configuration.
*/
public function onPluginsInitialized()
{
if ($this->isAdmin()) {
$this->active = false;
return;
}
$this->enable([
'onPageContentRaw' => ['onPageContentRaw', 0]
]);
}
/**
* Add the lazyload JS and add supporting code to initialize it.
*/
public function onTwigSiteVariables()
{
$assets = $this->grav['assets'];
$assets->addJs('plugin://lazy/vendor/ls.native-loading.min.js');
$assets->addJs('plugin://lazy/vendor/ls.unveilhooks.min.js');
$assets->addJs('plugin://lazy/vendor/lazysizes.min.js');
$assets->addJs('plugin://lazy/lazy.config.js');
}
/**
* Add content after page content was read into the system.
*/
public function onPageContentRaw(Event $event)
{
/** @var Page $page */
$page = $event['page'];
$config = $this->mergeConfig($page);
if ($config->get('enabled')) {
// Get raw content and substitute it for markup
$raw = $page->getRawContent();
$pattern = '/(?:^\[plugin:lazy]\()(.*)(?:,)(.*)(?:\))/m';
$replacement = '<section class="highlight">
<img
alt="$2"
src="{{ page.media[\'$1\'].quality(1).url }}"
data-sizes="auto"
data-src="{{ page.media[\'$1\'].url }}"
class="image lazyload"
loading="lazy"
/>
</section>';
$raw = preg_replace($pattern, $replacement, $raw);
$page->setRawContent($raw);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment