Show Fallback Image If No Image Selected
Whether you’re building a User Profile, Event, or Course Page you may find yourself in a situation where you’d like to give Content Editors the ability to select an Image from the Media Library to use in your content. If no image is selected, you may want to fall back to a “default” image to retain some consistency in your designs.
With Handlebars we can create our layouts with exactly this kind of logic.
Outputting a fallback image
The first step is to upload your default image to the Media Library. Once it’s uploaded, take a note of the ID
of the Media.
Now we edit our Content Layout. In this example I’ve got a simple Event Content Type with the following elements:
Name | Type | Size | Required |
---|---|---|---|
Event Title | Plain Text | 150 | Yes |
Event Date | Date | 80 | Yes |
Event Description | HTML | 10000 | Yes |
Event Image | Media | 80 | No |
Notice that the Event Image element is not required. This allows us to fall back to a default image if one isn’t selected like so:
What this does
This code will first check that the user has selected an image in the “Event Image” element.
If they have, we’ll output that image (using an alternate Media layout called image/event
).
If they haven’t, then we’ll output an alternate image by referencing its ID directly.
Back to top