Craft CMS Asked by Matt Wilcox on January 29, 2021
How Craft reacts to missing images is one of the very few places where I find Craft less than ideal.
TL:DR;
Long version:
There are a number of ways images can be missing, for example:
Any of these result in instances of ‘blahblah.jpg could not be found’ in Dev mode or Internal Server Error in production. Sometimes those images actually get lost; they just don’t exist any more; but they’re in the database. So…
How do you find what element is referencing these lost files? Besides manually trawling through entries, related entries, etc? Crafts error gives no useful information about that, and rebuilding asset indexes doesn’t seem to make Craft aware that the image isn’t available anymore.
And…
Is there an option to just ignore these types of error – it’s not helpful in production to have a whole page ‘internal server error’ just because a single image referenced on the page is missing from the file system for whatever reason. A missing image is not a throw-the-baby-out-with-the-bathwater problem.
I do all images through a macro, that substitutes in our logo if an image happens to be missing.
{% macro imageTransform(image, transform, caption, extraHTML) %}
{# Fallback to our logo if the image is null... #}
{% if not image|length %}
{% set image = craft.assets.id('84').first() %}
{% endif %}
<img src="{{ image.getUrl( transform ) }}" width="{{ image.getWidth( transform ) }}" height="{{ image.getHeight( transform ) }}" title="{{ caption|default('') }}" alt="{{ caption|default('') }}"{% if extraHTML %} {{ extraHTML }}{% endif %}>
{% endmacro %}
We have a more complicated version for responsive images but that's the basic idea...
Also, to find things using assets, although I have never used it, I hear this is good: https://github.com/iainurquhart/craft_introvert
Answered by Jeremy Daalder on January 29, 2021
If it's any help I made a quick plugin to handle this by way of a Twig extension. https://github.com/moresoda/existential
You can use it to test for the existence of a file with
{% if asset.getUrl() | fileExists %}
Answered by foamcow on January 29, 2021
Craft 3.5 introduced a new config setting - brokenImagePath
to deal with exactly this scenario.
https://craftcms.com/docs/3.x/config/config-settings.html#brokenimagepath
Answered by James Smith on January 29, 2021
Get help from others!
Recent Answers
Recent Questions
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP