ReadDir not return filename?

I’m trying to pick up a random image as featured image in archetypes/ like this

image: “{{ readDir “cool-images”|shuffle|first 1}}”

but what I get is

image: “[0xc00091b380]”

via , readdir should return file name , not something like this , it’s more like a inode number ??

so , is there any other way to convert the string to real filename ?
or any other way to pick up one random filename in dir ?

Your syntax is wrong. image: “{{ readDir “cool-images”|shuffle|first 1}}”
You cannot call shuffle along with the readDir function and filtering i.e. first 1 is typically used in tandem with the range function.

You need to see this answer:
- First read the directory
- Then range through its files
- Then use shuffle
- Then get the first one

To render the filename:
Within the scope of the readDir function
- First you will need to construct its PATH
- Use the relevant File Variables

These are the steps that you need to follow.

But with the above said, I’m confident that you could achieve your stated objective in a simpler way, like by organizing those images in Page Bundles and then using Hugo’s internal Image Processing methods.

@alexandros that doesn’t look entirely correct. Let me try to do a shorter version:

readDir returns a slice of

So you need to do something ala:

{{ $dir := "cool-images" }}
{{ $images := readDir $dir | shuffle }}
{{ $first := index $images 0 }}
{{ $path := path.Join $dir $first.Name }}

I created this issue to make this function a little easier to use:

But @alexandros is correct about the resources, and I suspect that putting the images in /assets and using resources.Match etc. would make it easier.

1 Like

Right. Thanks for the correction.