Access to module in modular page in php [Custom Shortcode]

Hello,

i have made a custom shortcode to lazyload some images with the shortcode-core plugin.

Here my code :

<?php
namespace Grav\Plugin\Shortcodes;
use Thunder\Shortcode\Shortcode\ShortcodeInterface;

class lazyloadImageShortcode extends Shortcode
{
  public function init()
  {
    $this->shortcode->getHandlers()->add('lazyload-image', function(ShortcodeInterface $sc) {

      $image = $this->getImage($this->grav['page'], $sc->getParameter('image'));

      return $this->twig->processTemplate('partials/lazyload-image.html.twig', [
        'image' => $image,
        'fullwidth' => $sc->getParameter('fullwidth'),
        'figcaption' => $sc->getParameter('figcaption'),
        'class' => $sc->getParameter('class'),
        'alt' => $sc->getParameter('alt'),
        'width' => $this->config->get('plugins.lazy-load.width'),
      ]);
    });
  }

  public function getImage($page, $media){
    return $page->getMedia()->get($media);
  }
}

It works well in normal page but nothing appears in modular page. I tried to debug and $this->grav[‘page’] can’t find the page object in modular page.

Someone can help me ? I specify, I’m not a developer, I tried to get inspiration from the code of other plugins to design this little piece of code. I think I need to test if the page is modular or not…

Thanks

1 Like

@Taver, That’s how modulars work…

Try to add some logic to the shortcode and test if the $page is a modular and if it is a modular, loop through its collection.

Something along the lines of…

$page = $this->grav['page'];
// When $page is modular
$collection = $page->collection();

foreach ($collection as $module) {
  $image = $this->getImage($module, $sc->getParameter('image'));
  // etc.
}

This loop will only run once when the page is being initialized and cached.