skip to Main Content

When I provided the contents in different md files called post1 and post2, I would like to add each content to my components called Service. When I do it like I describe below, I am having an error on my component page says title is not defined. How can I add those content automatically?

my page file:

---
import Layout from '../layouts/Layout.astro';
import { getCollection } from "astro:content";
const allPosts = await getCollection("posts");
import Service from "../components/Service.astro";
---

<Layout title="Serwis">
    <ul>
        {
             allPosts.map((post, index) => (
                <Service key={index} title={post.title} price={post.price} description={post.description}/>
            ))
          }
    </ul>
</Layout>

post1 md file:

---
title: Konserwacja Klimatyzatora    
description: Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas tincidunt, lacus sit amet ullamcorper feugiat, neque augue vulputate dui, vel condimentum justo nunc a ipsum.
price: Już od ...PLN
---

my component:

---
import Layout from '../layouts/Layout.astro';
---

<Layout title="Service">
    <div>
        <h2>{title}</h2>
        <p>{price}</p>
    </div>
    <p>{description}</p>
</Layout>

2

Answers


  1. Your Service.astro component should look for example like:

    ---
    import Layout from '../layouts/Layout.astro';
    
    const { title, price, description } = Astro.props
    ---
    
    <Layout title="Service">
        <div>
            <h2>{title}</h2>
            <p>{price}</p>
        </div>
        <p>{description}</p>
    </Layout>
    

    Or instead of having three different props (title, price, description) you could have just one (post), and call it like <Service post={post} />.

    Login or Signup to reply.
  2. The frontmatter for your collection entries can be accessed using post.data.title instead of post.title

    Collection Entry Reference

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search