Dynamic Routing in Eleventy
Set up a catch-all route strategy in your Eleventy project to render new stories dynamically.
Fetch a story dynamically
Section titled “Fetch a story dynamically”Create a _data/pages.js file to fetch all stories within your Space.
import storyblok from '../_utils/storyblok.js';import Feature from '../_components/feature.js';import Teaser from '../_components/teaser.js';import Grid from '../_components/grid.js';
export default async function pages() { const response = await storyblok.getAll('cdn/stories', { version: 'draft', // or "published" content_type: 'page', });
return response.map((story) => { const permalink = story.slug === 'home' ? '/' : `/${story.full_slug}/`; const name = story.name; const body = story.content.body .map((blok) => { switch (blok.component) { case 'feature': return Feature(blok); case 'teaser': return Teaser(blok); case 'grid': return Grid(blok); default: throw new Error(`Could not resolve ${blok.component} block.`); } }) .join('');
return { permalink, name, body, }; });}Define a permalink for each page, making an exception for our home story to be located at /.
Render all stories
Section titled “Render all stories”Create a pages.md file that will act as a content entry point.
---layout: 'layouts/base.liquid'pagination: data: pages size: 1 alias: itemeleventyComputed: title: '{{ item.name }}'permalink: '{{ item.permalink }}'---
<main> {{ item.body }}</main>With the Eleventy’s Pagination API, iterate over the array returned by the pages data function.
Use this data in the content area or pass properties down to the layout template with the eleventyComputed feature.
With this approach, your project can automatically handle new stories you add to your Space.
Related resources
Section titled “Related resources”Get in touch with the Storyblok community