Image urls with kql in headless

I’m using kirby as a headless cms and trying to get the image urls of a file field, but somehow can’t make it work.
Here is the select statement of kql:

select: {
      content: {
        "*": true,
        image_hero: {
          select: {
            url: true,
          },
        },
      },
    },

ideally it should fetch all fields, and when it’s a file or image get back the url and alt values.
I couldn’t find anything in the documentation about it, and also Ai was not helpful so far.

You need to convert the files field content to a files collection via .toFiles.

  "select": {
    "files": {
      "query": "page.myFileField.toFiles",
      "select": {
        "url": true,
        "alt": true,
      }
    }
  }

That looks promising, but when using the files array, the keys are lost.

Ideally all fields from content (not files) should be returned, only if it’s an image field, the URL and alt should be returned as well. Is that possibel?

You will need to tell Kirby the filenames of the field that you want to convert into file objects. Kirby otherwise will not know which field just holds text and which fields should it apply .toFiles to.

Telling kirby the filenames? But when the filename in the backend changes (coz someone uploads a different file), I would need to change the frontend code as well. Does not sound like a good idea.

The solution I came up with is this:

const kqlSelect = {
  url: true,
  uid: true,
  title: true,
  slug: true,
  content: true,
  image_hero: {
    query: "page.image_hero.toFile",
    select: imagesSelect,
  },
 image_section2: {
    query: "page.image_section2.toFile",
    select: imagesSelect,
  },
//..... more code
}

Just doesn’t seem like a nice solution to me, coz I need to specify each image field I want to get from the backend.

Sorry, not filenames, just the names of the fields (not sure what happened there, why I wrote filenames). As in your example.

For Kirby to know what fields are of type files, the whole blueprint would need to be loaded which isn’t great for performance. But you probably could implement this in a custom page method (load blueprint, loop through all fields and filter out files fields, use these names and apply toFiles() method to them, return all those files).

Ok, thanks for clarifying. :+1:t3: