0

My site just suddenly broke down on a certain page with the following error code, (see screenshot).

enter image description here

It is occuring for every image on this page and really confusing me.

Any quick suggestions?

3

For whatever reason, your site isn't able to find the image. And since your Twig code isn't being defensive, it's failing ungracefully.

{% set image = block.media.first() %}

This first part is fine... I'm assuming that media is an Assets relationship field. You're attempting to fetch the first asset, and set that to image. Here's the kicker... when no assets are found, image will be set to NULL.

This next part is where your problem is...

{{ image.url }}

That'll work great assuming an asset was found. But when no assets were found, this will trigger an error. Because image would be set to NULL, and NULL doesn't have an attribute of url. (This is exactly what the error message is telling you.)

Instead, you should write that line more defensively...

{{ image ? image.url }}

This technique uses the ternary operator to first check "if image is truthy" before attempting to output image.url. In other words, if image contains a valid asset, output the image URL.

That way, if no asset is found, you won't get a big nasty error message.


On a separate note... You seem to be expressing some urgency that your site has gone down. But the screenshot you showed is clearly a byproduct of being in devMode. For the record, you never want to have devMode enabled in a live production environment.

|improve this answer|||||
2

It's a bit hard to tell from this snippet, but if image is an asset field it's important to remember that these are returned as arrays so you have to access the url more like block.image.first().url. However, if the image variable is set elsewhere this probably won't help.

EDIT: Relevant docs

|improve this answer|||||

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.