Thumb() doesn't work for me

I don’t get it. Why doesn’t the following echo the URL to the resized file?

// Cover photo
$image = $page->cover_photo();
    echo $image; // this echos myphoto.jpg which is in the content folder
    echo '<p><img src="' . thumb($image, array('width' => 400))->url() . '" alt="photo"></p>';

This works with the new thumb API…

// Cover photo
$image = $page->cover_photo();
    echo '<p><img src="' . $page->image($image)->width(400)->url() . '" alt="photo"></p>';

I’m using 2.3. Perhaps I must use the new thumb API?

It doesn’t work because $image is just a string in the first example. You can use the toFile() method as an alternative to the second example.

$image = $page->cover_photo()->toFile();
if($image->isNotEmpty()): ?>
   <p><img src="<?= thumb($image, array('width' => 400))->url()  ?>" alt="photo"></p>
<?php endif; ?>

This creates an image object.

Just on a side note: I’d recommend not echoing HTML tags, it’s not really good practice.

Gotcha. So $image needs to be an object. Thanks for your wisdom.

Echoing HTML is poor form? All those <?php and ?> get under my skin, but I suppose all those echos become an issue too. hmmmm.

It might not seem to make such a big difference, but once the code is more complicated, it gets difficult to get all this string chaining right.

But the main reason why it is poor practice it that logic (PHP code) and presentation (HTML code) should be strictly separated.

Gotcha. Thanks again for you replies. Very helpful.

1 Like