Hello! I am trying to use filterBy() inside a src attribute of an img tag, but it is not working…
Here is my code.
<?php foreach($page->children() as $subpage): ?>
<div class="project-list-item">
<a href="<?php echo $subpage->url() ?>">
<div class="project-list-item-image">
<img class="lozad" src="<?= $subpage->images()->filterBy('filename', '*=', 'listing_l')->placeholderUri() ?>" data-src="<?= $subpage->images()->filterBy('filename', '*=', 'listing_l') ?>" data-lazyload>
</div>
<p class="list-tile-text list-tile-title fade-in-on-entry-slow">
<span><?php echo $subpage->title() ?></span>
</p>
<p class="list-tile-text list-tile-intro fade-in-on-entry-slow">
<?php echo $subpage->subtitle() ?>
</p>
</a>
</div>
<?php endforeach ?>
It works inside the data-src attribute, but not inside src
Moving filterBy() after placeholderUri() doesn’t work either.
If I remove filterBy() from the src attribute it gives me the first image.
Also, in case you are wondering, the placeholderUri() is for the Blurry Placeholder plugin:
🖼 Blurry image placeholders for better UX
Thanks !
filterBy() returns a collection and you cannot call a file method on a collection. So if this is supposed to return multiple images you would have to loop through the filtered result set.
<?php
$images = $subpage->images()->filterBy('filename', '*=', 'listing_l');
foreach ( $images as $image ) : ?>
<img class="lozad" src="<?= $image->placeholderUri() ?>" data-src="<?= $image->url() ?>" data-lazyload>
<?php endforeach ?>
1 Like
ok great, thanks for that that worked perfectly!
That explains why I can’t get it to work in a picture tag either…
<picture>
<source class="lozad" media="(min-width:1200px)" srcset="<?= $page->image('banner_l.jpg')->placeholderUri() ?>" data-src="<?= $page->image('banner_l.jpg')->url() ?>" data-lazyload >
<source class="lozad" media="(min-width:800px)" srcset="<?= $page->image('banner_m.jpg')->placeholderUri() ?>" data-src="<?= $page->image('banner_m.jpg')->url() ?>" data-lazyload >
<img class="lozad" src="<?= $page->image('banner_s.jpg')->placeholderUri() ?>" data-src="<?= $page->image('banner_s.jpg')->url() ?>" data-lazyload >
</picture>
I’m not sure if it is clear to you from the above code what I am trying to achieve ?
sorry, php is not my strength, I have been trying out different approaches, but I cant figure out how to apply your solution to a picture tag with multiple sources… any ideas ?
My code above just gives me the banner_s image each time, regardless of my viewport size.