Nested Dynamic Routing in Astro

Example of nested dynamic-routing

Intro

Example to work with nested (or multi) dynamic routing.

We will generate some pages using the following JSON:

[
  { "make": "ford",  "model": "focus",    "description": "a car", "image": "..." },
  { "make": "ford",  "model": "explorer", "description": "a car", "image": "..." },
  { "make": "ford",  "model": "fiesta",   "description": "a car", "image": "..." },
  { "make": "dodge", "model": "durango",  "description": "a car", "image": "..." },
  { "make": "dodge", "model": "caravan",  "description": "a car", "image": "..." },
  { "make": "honda", "model": "civic",    "description": "a car", "image": "..." },
  { "make": "honda", "model": "accord",   "description": "a car", "image": "..." },
  { "make": "honda", "model": "pilot",    "description": "a car", "image": "..." }
]

and we want our urls to be:

Astro page

We want to have our URLs like

https://domain/.../[make]/[model]

For this, our file structure should be:

+- [make]/ 
  +- [model].astro 

Directions

nodetypeinfo
(1)folder[make] - a folder
(2)file[model].astro - a file inside the [make] folder

[model].astro

---
import BaseLayout from './../../../../../layouts/BaseLayout.astro';
import makemodel from './makemodel.json'; 

export async function getStaticPaths() {
  let returnedAry = [];

  makemodel.forEach((entry) => { 
    returnedAry.push({
        // params for the url
      params: { make: entry.make, model: entry.model },
        // any props we want to send to page-level
      props: { 
        description: entry.description,
        image: entry.image
      }
    });
  });

  return returnedAry;
}

// page-level 
const { make, model } = Astro.params;
const { description, image } = Astro.props;
---
<BaseLayout title={`Car Page - ${make} ${model}`}>
  <h1>{make} <small>{model}</small></h1>
  <h3>{description} - {model} - {make}</h3>
  <img src={image} width="197" />
</BaseLayout>

<style>
img { border:9px solid #abd; }
</style>

Directions

noteinfo
(1)import our data
(2)iterate our data
(3)work on our params for the URL. We need a make and a model
(4)other props we want to make available at page-level
(5)start our page-level code

Output

These are the pages generated:

dist-output ixmage{"ignore":true}

Conclusion

Your data may not be as simple as my makemodel JSON example, and you may need to do an iteration inside an initial “outer” iteration.

The same principle applies to fill the returnedAry with the proper params.



Back to Post List
ok!