Assign file templates to already existing content?

Hi there,

in an existing project, I need to restructure my panel somewhat and I need to assign a template to images and videos that had not assigned any template so far. Is there a quick way to do this, without going through all the content files manually? Like, could Kirby not assign this automatically somehow, once there is a new File Blueprint that matches the file type? Am I missing something?

Thanks!
trych

A little script will do the job.

Is there any documentation on how such scripts can be written? I guess I have a vague idea that I will have to loop over every file on my site and update its template value, but where do I need to place the script? How do I run it?

Exactly.

I usually use either a route or simply put it into a template if I’m lazy (for one-time stuff)

Thanks, will give this a try and report back.

Wait, how do I loop over all files of the entire web page? I thought I need to loop over $site->files() but that only gets me the files that are stored on the top level.

$site->index()->files()

Might make sense to filter by type etc. to assign different templates.

If you have thousands of files, doing it in chunks might make sense.

Ah, found it. I ended up doing this:

foreach ($site->index() as $page) {
  foreach ($page->files() as $file) {
    if(!$file->template()) {
      $file->update([
        'template' => 'media'
      ]);
    }
  }
}

Worked very well. Thanks @pixelijn!

Ah, didn’t see your answer in time. I worked really well like this. If I have thousands of files in the future, I will keep in mind to utilize filters. Thanks!