Technically you could do all this in Volt, done it myself few times, but after coming back to support these projects I had to read my code few times to understand what I really wanted to do. Here is an old example: http://www.orangefitness.bg/orange/varna Perhaps this gallery is even funkier than the one you have to make :)

Also having least possible logic in your templates will make your frontend developer happy ;)

Here is how i would do it, the PHP code can be placed in a Helper function, gallery model or whatever.