Skip to content

Commit 9bcfcbf

Browse files
committed
readme 14
1 parent ca89761 commit 9bcfcbf

1 file changed

Lines changed: 82 additions & 0 deletions

File tree

Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
# Astro API
2+
3+
Vamos a ver como podemos hacer para poder leer listas de ficheros en nuestro proyecto Astro.
4+
5+
En concreto vamos a leer la lista de posts que tenemos y mostrarla en una página de listado de posts.
6+
7+
# Manos a la obra
8+
9+
Tenemos una página con un listado de posts `blog.astro`, vamos a leer lost posts de la lista de markdowns que tenemos y mostrarlos.
10+
11+
_./src/pages/blog.astro_
12+
13+
```diff
14+
---
15+
import BaseLayout from "../layouts/base.astro";
16+
17+
+ // This could be moved to common model and share it with the
18+
+ // blog layout
19+
+ interface Frontmatter {
20+
+ layout: string;
21+
+ title: string;
22+
+ pubDate: string;
23+
+ description: string;
24+
+ author: string;
25+
+ image: {
26+
+ url: string;
27+
+ alt: string;
28+
+ };
29+
+ tags: string[];
30+
+ }
31+
32+
+ const allPosts = await Astro.glob<Frontmatter>("./posts/*.md");
33+
---
34+
35+
<BaseLayout pageTitle="Blog">
36+
<h2>Aqui va mi listado de posts</h2>
37+
<ul>
38+
<li><a href="/posts/post-1/">Post 1</a></li>
39+
<li><a href="/posts/post-2/">Post 2</a></li>
40+
<li><a href="/posts/post-3/">Post 3</a></li>
41+
</ul>
42+
</BaseLayout>
43+
```
44+
45+
Y mostramos todos los posts que tenemos en la lista:
46+
47+
_./src/pages/blog.astro_
48+
49+
```diff
50+
51+
<BaseLayout pageTitle="Blog">
52+
<h2>Aqui va mi listado de posts</h2>
53+
<ul>
54+
- <li><a href="/posts/post-1/">Post 1</a></li>
55+
- <li><a href="/posts/post-2/">Post 2</a></li>
56+
- <li><a href="/posts/post-3/">Post 3</a></li>
57+
+ {allPosts.map((post) => <li><a href={post.url}>{post.frontmatter.title}</a></li>)}
58+
</ul>
59+
</BaseLayout>
60+
```
61+
62+
Para ver que esto funciona, vamos a crear un cuarto post:
63+
64+
_./src/pages/posts/post-4.md_
65+
66+
```md
67+
---
68+
layout: ../../layouts/markdown-post.astro
69+
title: Cuarto Post
70+
author: Lemoncode
71+
description: "Este post lo creamos y se muestra del tirón"
72+
image:
73+
url: "https://docs.astro.build/default-og-image.png"
74+
alt: "The word astro against an illustration of planets and stars."
75+
pubDate: 2022-08-08
76+
tags: ["astro", "successes"]
77+
---
78+
79+
Este es el cuarto post, si tenemos el proyecto arrancado, se regenerará y mostrará este cuarto post
80+
```
81+
82+
Y ahora podrás pensar, oye es que me quiero mostrarlo ordenado por fecha, pues, lo tienes fácil, la lista la tienes tipada junto con sus campos del front matter y podrías hacer un sort por el campo fecha.

0 commit comments

Comments
 (0)