You don't have access to this class

Keep learning! Join and start boosting your career

Aprovecha el precio especial y haz tu profesión a prueba de IA

Antes: $249

Currency
$209
Suscríbete

Termina en:

0 Días
21 Hrs
59 Min
33 Seg

Creando template de nuestra página de entrada del blog

17/25
Resources

How to create an elegant template with Astro and Tailwind?

Astro and Tailwind are powerful tools for developing web components with high efficiency and aesthetics. If you are looking to take your content to the next level, this detailed guide will teach you how to create an elegant template using these technologies. By following the right approach, you will be able to present your content in a structured and eye-pleasing way.

Where to find the best components?

When looking for sections that suit the content you want to create, Hyper UI is an excellent option for choosing Tailwind components. This platform offers a variety of sections, providing titles, images and areas where you can include complete content. Simply choose the component that best suits your needs and copy it to incorporate it into your project.

How to integrate a new template into your Astro application?

First, go to your code editor, in this case Visual Studio Code, and create a new file, which we will call post.astro. This file will contain the resource just copied from Tailwind.

Inside post.astro, start by setting up the necessary logic in JavaScript. Create a constant to import elements like title, date, image and tags from the Astro API and props.

const { title, date, image, tags } = content;

Once the elements to be rendered are defined, remove the predefined sections and replace them with those that will use this dynamic data.

How to organize the content with Tailwind?

When using Tailwind, it is essential to organize the content so that it is responsive and displays correctly on all devices. Use Tailwind classes that allow you to adjust elements such as flex, flex-row, gap, among others, to manage the content layout.

// Example class configuration<div className="flex flex-col md:flex-row items-center md:gap-4"> <img src={image}  alt={title} /> <div><h2>{title}</h2> <time className="text-sm">{date}</time> <div className="tags">{tags}</div> </div> </div></div> </div>.

Check the design in different resolutions to make sure that the content adapts well regardless of the screen size.

How to improve the design and functionality of the template?

To improve the structure of the template, encapsulate the content within the base of the site. It is essential to include a header, a footer and possibly social sharing options to complete the design properly. By integrating these elements, you ensure that the site maintains a professional and coherent appearance.

How to manage dynamic images?

To handle images dynamically, use an API that provides images with different parameters. This ensures that each post or resource has unique images without additional effort.

<img src={`https://api.unsplash.com/photos/random?client_id=${YOUR_ACCESS_KEY}`} alt={title} />

What's next in improving the project?

Finally, consider integrating libraries such as React, Vue or Svelte, as Astro has the ability to combine them, giving you a variety of options to enrich the functionality of your project. Continuing to learn and experiment with these technologies will allow you to create more robust and attractive applications.

Explore these concepts to get the most out of contemporary web development. The tools are at your disposal; the limit is only in your creativity and willingness to learn.

Contributions 8

Questions 0

Sort by:

Want to see more contributions, questions and answers from the community?

Clase del span Posts.astro:

<span class="flex flex-col sm:gap-y-2 md:flex-row md:items-center md:gap-y-0 md:divide-x md:divide-textColor">

Me queda la duda sobre la clase md:divide-textColor, estuve buscando en la documentación de Tailwind y esa clase no existe. Quizás es una clase personalizada que tiene el profesor, pero igual la puse 😁

hola, como se genera un comentario dentro del archivo.astro?

Layouts

Durante el análisis de un sitio o plataforma web, podemos reconocer una organización y distribución del contenido.
.
Cada elemento en la visualización de una página o vista, requiere que exista una regla que permita armonizar, incluso equilibrar el contenido según sea el impacto que se desee dar, por ejemplo responsive vs adaptive.
.

ℹ️ Definición
Los Layouts son referencias que nos permite organizar y distribuir el contenido, dado un punto de inicio más una dirección de creación.

.

Análisis de Layouts

Los layouts, son considerados tanto plantillas como delimitadores donde lucen por su facilidad de implementación y flexibilidad para su personalización.
.
Supongamos la siguiente vista:
.

.
De lo anterior, podemos denotar grupos de contenido que puede describirse en una página (en este caso de productos). Con ello, cuando navegamos entre los diferentes productos, se reutiliza dicha plantilla como página base.
.
Este tipo de Layout, sirve para la organización de páginas o vistas.
.
En acto, el análisis anterior sirve como preliminar para poder reconocer los orígnes del contendio anterior. Con ello, nos permitimos la identificación de bloques estáticos y dinámicos.
.
Por su parte, requerimos un tipo de Layout para que pudiéramos distribuir el contendio anterior.
.

.
Un Layout distributivo nos permite composicionar el contenido para, según su visualización e importanciía, se pueda agrupar para su “maquetación”.
.
De la imágen anterior, podemos estipular una grilla de columnas y filas para su facilidad de implementación.
.

Desarrollo de Layouts

ⴵ Repositorio - Coffeeroasters

⬢ Commit - feat: ✨ added content page

.
Recordemos que con Tailwind, podemos personalizar un tema de estilos basados en un sistema de diseño.
.
Lo más común, al generar Layouts en CSS es mediante Grid Layout y Flex Box. De ello, generamos mediante plugins una utilidad de Tailwind para la facilidad de implementación de ambos Layouts de CSS.
.

const plugin = require('tailwindcss/plugin')

module.exports = plugin(function ({ matchUtilities, theme }) {
    matchUtilities({
        'grid-columns': (value) => ({
            display: 'grid',
            gridTemplateColumns: `repeat(${value}, minmax(0, 1fr))`,
            columnGap: theme(`spacing.2`),
            placeContent: 'center',
        }),

        'flex-column': (value) => ({
            display: 'flex',
            flexDirection: 'column',
            gap: theme(`spacing.${value}`),
        }),
        'flex-row': (value) => ({
            display: 'flex',
            gap: theme(`spacing.${value}`),
        }),
    })
})

✨ Concepto clave
Una utilidad nos permite registrar un tipo espcial de clases para Tailwind. Se recomienda en casos donde la implementación en línea, de varias clases, limita el desarrollo.

.
Una vez registrada la utilidad como parte de nuestro archivo tailwind.config, podemos emplearla para la creación de Layouts distributivos.
.
Supongamos una página dínámica de Astro, donde empleamos ./src/products/[slug].astro para la generación dinámica de nuestro contenido, tomando las colecciones como información:
.
./src/products/[slug].astro

---
import { getCollection, getEntryBySlug } from 'astro:content'
import Default from '@layouts/default.astro'

export function getStaticPaths() {
    return [
        { params: { slug: 'danche' } },
        { params: { slug: 'gran-espresso' } },
        { params: { slug: 'piccollo' } },
        { params: { slug: 'planalto' } }
    ]
}

const { slug } = Astro.params
const product = await getEntryBySlug('products', slug)
const products = await getCollection('products',
    ({ data }) => {
        return data.title !== product.data.title
    })
---

<Default></Default>

Con la definición anterior, podemos sesgar la información para traernos las imágenes necesarias y omitiendo la vista actual. Adicionalmente, consultamos la información de nuestro producto, según la vista en curso.
.
En distribiución, podemos emplear nuestra utilidad de Tailwind y ajustando nuestros bloques. Por ejemplo:
.
./src/products/[slug].astro

---
import { getCollection, getEntryBySlug } from 'astro:content'
import Default from '@layouts/default.astro'

export function getStaticPaths() {
    return [
        { params: { slug: 'danche' } },
        { params: { slug: 'gran-espresso' } },
        { params: { slug: 'piccollo' } },
        { params: { slug: 'planalto' } }
    ]
}

const { slug } = Astro.params
const product = await getEntryBySlug('products', slug)
const products = await getCollection('products',
    ({ data }) => {
        return data.title !== product.data.title
    })
---

<Default>
    <main>
        <section class='grid-columns-[12]'>
            <div class='col-start-2 col-span-2 flex-column-[4]'>
                {products.map(product => (
                    <a class='gallery-item' href=`/products/${product.slug}`>
                        <img src={product.data.image} alt={product.data.title} />
                    </a>
                ))}
            </div>

            <div class='col-span-8 grid-columns-[8]'>
                <img class='col-span-4'
                     src={product.data.image} alt={product.data.title} />

                <div class='col-span-4 flex-column-[3]'>
                    <div class='flex-column-[1]'>
                        <h2>{product.data.title}</h2>
                        <p>{product.body}</p>
                    </div>

                    <div class='flex-column-[1]'>
                        <h3>Quantity</h3>
                        <div class='grid-columns-[2]'>
                            <p>$29.00</p>
                            <p>${product.data.price.toFixed(2)}</p>
                        </div>
                    </div>
                    <div class='grid-columns-[2]'>
                        <Button text='Buy it now' />
                        <Button variant='outline' text='Add to cart' />
                    </div>
                </div>
            </div>
        </section>
    </main>
</Default>

Se notará el uso de nuestro Layout distributivo, donde como Layour organizaciónal empleamos default.astro para simplemente disponer de nuestro contenido.

la funcionalidad de layout en los .md no me funciona en astro 5, baje la versión de este proyecto y tampoco funciono 🤔
Alguien le pasa que no le funciona Lorem.space?, resulta que no me cargan las imagenes
Les comparto la API, creada por Platzi (estudiantes): <https://fakeapi.platzi.com/>

Este es mi Tag component

---
export interface Props {
	tags: string[];
}

const { tags } = Astro.props;
---

{
	tags.map((tag) => (
		<span class="whitespace-nowrap rounded-full bg-purple-100 px-2.5 py-0.5 text-xs text-purple-600">
			{tag}
		</span>
	))
}