Is there any way to randomly assign an image at Hugo build time? I have the random images in my /static/img folder, and they’re file-named 1.jpg, 2.jpg, 3.jpg, etc. This doesn’t need to be pretty; any work-around will suffice.
Honestly, I’d just write a shell script to do it.
I don’t think there are any random functions exposed in the templates, but it is possible to be a little creative with the time API.
{{ add 1 (div .Now.Second 6) }}.jpg
Should give:
[1..10].jpg
You said it didn’t have to be pretty
Or maybe some simple JavaScript?
Run something like this prior to every build and have your template always use the “randomImage.png” file.
#!/bin/bash
# copy a random .png file to "randomImage.png"
# assumes we're in the directory to copy to.
# will be a noop if there are no .png files.
# will not select the displayMe.png file as both src and tgt.
tgt="randomImage.png"
src=$( find . -type f -name '*.png' | grep -v "^${tgt}\$" | sort -R | sed 1q )
[ -f "${src}" ] && cp "${src}" "${tgt}"
Not to necro an old post, but I’m trying to do exactly this and getting an error:
ERROR: 2016/04/14 template: partials/page-header.html:2:2: executing
"partials/page-header.html" at <div .Now.Second 10>: error calling div:
Can't apply the operator to the values in partials/page-header.html
Relatively new to Hugo (and this, Golang), so I’m totally lost on this one…
If you want to “necro” an old post like this, you would have to provide more context. And error message is only good enough for prophets.
If I put {{div .Now.Second 10}}
anywhere a template, I get that error. If you really want to see the full source you can but it’s irrelevant.
It works fine for me. I noticed that you’re in a partial template. Make sure you’re passing a page into the partial as the initial context.
{{ partial "page-header.html" . }}
OK, then.
On an added note, in the latest Hugo (0.16-DEV, not released) there is a shuffle func, so you can do something like:
{{ readDir "cool-images" | shuffle | first 1 }}
hello, sorry to re-necro this post,
i am really new to hugo and to coding in general i guess,
i made a .md file inside my content folder, and i would like to have it showing a random .jpg from a set of .jpgs contained in a folder inside the static folder.
could you please help me ?
thank you and eventually sorry for my english