#[lang] and another slug from collection

4 messages · Page 1 of 1 (latest)

sleek shale
#

I have the following structure

src/pages/[lang]/pizzas/[pizza].astro

and the following getStaticPaths for this file

export async function getStaticPaths() {
  const pizzas = await getCollection("pizzas");
  return pizzas.map((pizza) => ({
    params: {
      pizza: pizza.data.name.toLowerCase(),
    },
    props: { pizza },
  }));
}

the problem is that name.toLowerCase() doesn't work because it is an object of keys of different languages than when passed i.e. pizza.data.name['es'].toLowerCase() then works.

how to fix?

slender pondBOT
#

Hi @sleek shale. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

To address your issue with multilingual content in Astro collections, you need to modify your getStaticPaths function to handle the language-specific data correctly. Based on the information provided in the knowledge sources, here's how you can adjust your code:

---
import { getCollection } from 'astro:content';

export async function getStaticPaths() {
  const pizzas = await getCollection("pizzas");
  const languages = ['en', 'es']; // Add all your supported languages here

  return languages.flatMap((lang) =>
    pizzas.map((pizza) => ({
      params: {
        lang,
        pizza: pizza.data.name[lang].toLowerCase(),
      },
      props: { pizza },
    }))
  );
}

const { lang, pizza } = Astro.params;
const { pizza: pizzaData } = Astro.props;
---

<!-- Your page content here -->

This solution addresses your problem by:

  1. Defining an array of supported languages.
  2. Using flatMap to create routes for each pizza in each language.
  3. Accessing the language-specific name using pizza.data.name[lang].

This approach is based on the dynamic routing patterns described in the Dynamic Routes documentation. It allows you to generate pages for each pizza in each supported language.

Remember to adjust the languages array to include all the languages you support in your project.

Also, make sure that your content collection schema for pizzas is set up correctly to handle multilingual content. You might want to structure your pizza data like this:

import { z, defineCollection } from 'astro:content';

const pizzaCollection = defineCollection({
  schema: z.object({
    name: z.object({
      en: z.string(),
      es: z.string(),
      // Add other languages as needed
    }),
    // Other pizza properties...
  }),
});
#

export const collections = {
pizzas: pizzaCollection,
};


This setup ensures that each pizza has a name for each supported language, which you can then access and use in your `getStaticPaths` function.
----------------------
Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:
----------------------