#Is it possible to grab all (or some) images under new `src/assets`?

5 messages · Page 1 of 1 (latest)

jagged spear
#

I'm trying to build a gallery-like demo site using new experimental assets feature. To do so I put a src/data/photos.json which contains metadata for each photo (file, credit, etc.), and create a dynamic routes that tries to import those files using dynamic import()s. And it doesn't work.

---
import { getImage } from 'astro:assets';
import Layout from '../../components/Layout.astro';
import photos from '../../data/photos.json';

export async function getStaticPaths() {
    return photos.map((item) => {
        return {
            params: {
                photo: item.url.slice(28), // stripping `https://unsplash.com/photos/`
            },
            props: {
                file: item.file,
                credit: item.credit
            },
        };
    });
}

const { file, credit } = Astro.props;
const image = await getImage({
    src: `../../assets/${file}`,
    width: 1000,
    height: 2000,
});

const title = `Photo by ${credit}`;
---

<Layout name={title}>
    <figure>
        <img src={image.src} />
        <figcaption>Photo by {credit}</figcaption>
    </figure>
</Layout>
mystic brook
#

Could you try Astro.glob('../../assets/**/*') to get an array of images?

#

Haven’t tried if that works with the new assets config or not

jagged spear
#

ah good point. will try!

jagged spear
#

I sort of get it working with Astro.glob()!

import photos from '../../data/photos.json';

export async function getStaticPaths() {
  const assets = await Astro.glob('../../assets/**/*.jpg');
  return photos.map((item) => {
    return {
      params: {
        photo: item.url.slice(28), // stripping `https://unsplash.com/photos/`
      },
      props: {
        credit: item.credit,
        url: item.url,
        image: assets.find((asset) => asset.default.src.includes(item.file))
          .default,
      },
    };
  });
}

it's a bit tedious to match an image against the globbed files. Is there a better way associating metadata alongside the assets?