簡體   English   中英

從 Astro 中的文件夾動態導入所有圖像

[英]Dynamically import all images from a folder in Astro

我正在與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} />)}

所以現在,要有一個新的收藏路線,我只需要創建一個新文件夾並將圖像放在那里。

有什么辦法可以達到相同的結果嗎? 提前致謝!!

有很多不同的方法可以實現這樣的功能,但這里是一個使用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.globimport.meta.glob()因為它可以將變量作為參數(使這個邏輯更容易/更動態)並且因為它只返回一個文件/文件夾路徑數組而不是也嘗試返回文件內容

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM