我在Astro工作。该项目使用了相当多的图像,我想简化我目前添加新图像的方式。我的路由如下:
example.com/pictures/(集合)
("[";和"]";表示动态路由)
允许例如:
example.com/pictures/mixed-tecnique
example.com/pictures/graphite
example.com/pictures/acrylic
在文件pages/pictures/[collection].astro
我想做以下(或类似的东西):
---
import * as collections from "public/img/collections"
const { collection } = Astro.props
---
{collections[collection].map(imgSrc => <img src={imgSrc} />)}
现在,要创建一个新的集合路径,我只需要创建一个新文件夹,并将图像放到那里。
有什么方法可以达到同样的结果吗?提前感谢!!
我是这样做到的:
---
const images = await Astro.glob("/src/assets/img/salon/*").then(files => {
return files.map(file => file.default);
});
---
<div class="swiper">
<!-- Additional required wrapper -->
<div class="swiper-wrapper">
<!-- Slides -->
{
images.map(image => (
<div class="flex items-center justify-center swiper-slide">
<img
class="object-contain h-full rounded-lg"
src={image}
alt=""
loading="lazy"
/>
</div>
))
}
</div>
...
</div>
如果您正在使用实验资产功能:
{
images.map(({ src /* width and height is also available */ }) => (
<div class="flex items-center justify-center swiper-slide">
<img
class="object-contain h-full rounded-lg"
src={src}
alt=""
loading="lazy"
/>
</div>
))
}
有很多不同的方法来实现这样的功能,但这里有一个简单的例子,利用fast-glob
库
public
pictures
mixed-technique
example.png
example.png
example.png
graphite
example.png
example.png
example.png
arcylic
example.png
example.png
example.png
// src/pages/pictures/[collection].astro
---
import fg from 'fast-glob';
export async function getStaticPaths() {
// get all collection folder paths: 'public/pictures/[collection]'
const collections: string[] = fg.sync('public/pictures/*', { onlyDirectories: true })
// Create a new route for every collection
return collections.map(collection => {
// Create Route
return {
params: {
// Return folder name of collection as dynamic parameter [collection]
collection: collection.split('/').pop()
},
props: {
// Return array of all image srcs in collection as prop 'images'
images: fg.sync(`${collection}/**/*.{png,jpg}`).map(img => img.replace('public/', '/'))
}
}
})
}
export interface Props {
images: string[];
}
const { collection } = Astro.params
const { images } = Astro.props
---
<html lang="en">
<head>
<!-- ... -->
</head>
<body>
{ images.map(img => <img src={img}/>) }
</body>
</html>
注意:我使用
fast-glob
而不是Astro.glob
或import.meta.glob()
,因为它可以将变量作为参数(使此逻辑更容易/更动态),并且因为它只返回文件/文件夹路径数组,而不是还试图返回文件内容