Skip to content
Grav 2.0 is officially stable. Read the announcement →

Community guidelines

Please keep discussions civil and on-topic. Repeated violations may lead to a temporary ban.

General

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

Started by Benjam 6 years ago · 1 replies · 495 views
6 years ago

Hello,

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

Here my code :

PHP
<?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
2 years ago

@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...

PHP
$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.

Suggested topics

Topic Participants Replies Views Activity
General · by Jerry Hunt, 4 days ago
2 80 9 hours ago
General · by pamtbaau, 14 hours ago
1 51 14 hours ago
General · by Andy Miller, 1 day ago
0 44 1 day ago
General · by Marcel, 12 months ago
6 346 5 days ago
General · by Duc , 5 days ago
3 40 5 days ago