Query for options for images in cards on a listing page

I have an image using a template(‘cover’) and a list of images using template(‘image’).

This works to show the “cover” image in the listing page for various articles:

image:
  query: page.files.template('cover').first

and when there is no cover image I want the card to have the “image” image. This works for that:

image:
  query: page.files.template('image').sort.first

I would like to use the “cover” image when there is one, and otherwise have the “image” image show in the cards.

In the Query Language docs I saw this and thought it would work:

page.title.isNotEmpty ? page.title.lower : page.slug

Is it possible to get the desired result in some way? I tried this but it didn’t work:

image:
  query: page.files.template('cover').first.isNotEmpty ? page.files.template('cover').first : page.files.template('image').sort.first

Thank you!

You can make your queries less complex by explicitly selecting ‘image’ instead of ‘files’ if you really only want to select images. Please try this code in your setup:

image:
  query: page.images.template('cover').first ?? page.images.template('image').first

Either the cover image or the first “image” image. Returns a file object or null if neither exists.

GB_DESIGN,

You’re solution is very elegant:

image:
  query: page.images.template('cover').first ?? page.images.template('image').first

When using the ‘image’ template I had hoped to show the image with sort characteristic ‘1’, which I called sort.first.

image:
  query:   page.images.template('cover').first ?? page.images.template('image').sort.first

This produced the same result, and didn’t use the sort number. In both cases, if I understand correctly, the first image alphanumerically will be used. I can force this renaming a given image in the files—not quite what I was looking for.

But I’m happy with it as is. If I want to force which image will show in the panel, I can enter a template(‘cover’) image. Still interested if there is a way to query by “sort”.

Yes, but you need to specify, what you want to sort by, so sort('sort') to sort by the sort number.