1

I have an astro project with several .astro pages in src/pages/topics/ in my src/pages/index.astro file I would like to have a nav list with a link to each of the topic pages. Is there a way to automatically get a list of all pages within the topic folder so I can iterate over it and generate my nav list in index.astro.

I had a look at collections but I don't think that would work as my topic pages need to be .astro files and collections only support .md files. I don't need the schema checking feature of collections but it's also not a problem as my topic files are all uniformly structured.

jpala
  • 83
  • 8

1 Answers1

1

Yes you can get the list of all pages within a folder in different ways

Solution options

But this is not recommended because it performs a complete import of all the files in an eager fashion

This way you get a list of any file type and the advantage is that you do not perform the actual import as you you get a promise to perform the import on demand, so it is more efficient

  • using the file system e.g. in node await fs.readdir(); but any env should have similar functions such as deno fs.

Examples with references

  • import.meta.glob()
const posts = import.meta.glob('../../../data/blog/**/*.{md,mdx}')//relative to this component file
const component_path = process.cwd()+'/src/pages/blog/'
const Post_path = Object.keys(posts).find((path)=>(resolve(component_path,path) == page_path))

https://github.com/MicroWebStacks/astro-big-doc/blob/45c2bafc85623ffab3c394609eb119e2693cd2ee/src/pages/blog/%5B...page%5D.astro#L27

  • filesystem
async function parse_dir_recursive(dir) {
    const subdirs = await fs.readdir(dir);
    const files = await Promise.all(subdirs.map(async (subdir) => {
      const res = resolve(dir, subdir);
      return (await fs.stat(res)).isDirectory() ? parse_dir_recursive(res) : res;
    }));
    return files.reduce((a, f) => a.concat(f), []);
}

Node.js fs.readdir recursive directory search

https://github.com/MicroWebStacks/astro-big-doc/blob/45c2bafc85623ffab3c394609eb119e2693cd2ee/src/layout/nav_section.js#L11

Note: the linked example https://github.com/MicroWebStacks/astro-big-doc has a use case identical to the question asked, generating a navigation menu from a list of files and even recursively within a directory hierarchy

wassfila
  • 1,173
  • 8
  • 18