Saltar al contenido

Añade contenido dinámico sobre ti

Ahora que tienes un sitio web multipágina con contenido HTML, ¡es hora de añadir algo de HTML dinámico!

Prepárate para…

  • Define el título de tu página en el frontmatter, y úsalo en tu HTML
  • Muestra elementos HTML condicionalmente
  • Añade algo de contenido sobre ti

Cualquier archivo HTML es lenguaje Astro válido. ¡Pero, puedes hacer más con Astro que solo HTML regular!

Abre about.astro, que debería verse así:

src/pages/about.astro
---
---
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width" />
<title>Astro</title>
</head>
<body>
<a href="/">Home</a>
<a href="/about/">About</a>
<a href="/blog/">Blog</a>
<h1>About Me</h1>
<h2>... and my new Astro site!</h2>
<p>I am working through Astro's introductory tutorial. This is the second page on my website, and it's the first one I built myself!</p>
<p>This site will update as I complete more of the tutorial, so keep checking back and see how my journey is going!</p>
</body>
</html>
  1. Añade la siguiente línea de JavaScript en el script del frontmatter, entre las vallas de código:

    src/pages/about.astro
    ---
    const pageTitle = "About Me";
    ---
  2. Reemplaza tanto el título estático "Astro" como el encabezado "About Me" en tu HTML con la variable dinámica {pageTitle}.

    src/pages/about.astro
    <html lang="en">
    <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width" />
    <title>Astro</title>
    <title>{pageTitle}</title>
    </head>
    <body>
    <a href="/">Home</a>
    <a href="/about/">About</a>
    <a href="/blog/">Blog</a>
    <h1>About Me</h1>
    <h1>{pageTitle}</h1>
    <h2>... and my new Astro site!</h2>
    <p>I am working through Astro's introductory tutorial. This is the second page on my website, and it's the first one I built myself!</p>
    <p>This site will update as I complete more of the tutorial, so keep checking back and see how my journey is going!</p>
    </body>
    </html>
  3. Actualiza la vista previa en vivo de tu página /about.

    El texto de tu página debería verse igual, y el título de tu página mostrado en tu pestaña del navegador ahora debería decir "About Me" en lugar de "Astro."

    En lugar de escribir texto directamente en etiquetas HTML, acabas de definir y luego usar una variable en las dos secciones de tu archivo .astro, respectivamente.

  4. Usa el mismo patrón para crear un valor pageTitle para usar en index.astro ("Home Page") y blog.astro ("My Astro Learning Blog"). Actualiza el HTML de estas páginas en ambos lugares para que el título de tu página coincida con el encabezado mostrado en cada página.

  1. Añade el siguiente JavaScript a tu frontmatter, entre las vallas de código:

    (Puedes personalizar el código para ti, pero este tutorial usará el siguiente ejemplo.)

    src/pages/about.astro
    ---
    const pageTitle = "About Me";
    const identity = {
    firstName: "Sarah",
    country: "Canada",
    occupation: "Technical Writer",
    hobbies: ["photography", "birdwatching", "baseball"],
    };
    const skills = ["HTML", "CSS", "JavaScript", "React", "Astro", "Writing Docs"];
    ---
  2. Luego, añade el siguiente código a tu plantilla HTML, debajo de tu contenido existente:

    src/pages/about.astro
    <p>Here are a few facts about me:</p>
    <ul>
    <li>My name is {identity.firstName}.</li>
    <li>I live in {identity.country} and I work as a {identity.occupation}.</li>
    {identity.hobbies.length >= 2 &&
    <li>Two of my hobbies are: {identity.hobbies[0]} and {identity.hobbies[1]}</li>
    }
    </ul>
    <p>My skills are:</p>
    <ul>
    {skills.map((skill) => <li>{skill}</li>)}
    </ul>
  1. El frontmatter de un archivo .astro está escrito en:

  2. Además de HTML, la sintaxis de Astro te permite incluir:

  3. ¿Cuándo necesitas escribir tu JavaScript dentro de llaves?

También puedes usar las variables de tu script para elegir si quieres o no renderizar elementos individuales del contenido de tu <body> HTML.

  1. Añade las siguientes líneas a tu script de frontmatter para definir variables:

    src/pages/about.astro
    ---
    const pageTitle = "About Me";
    const identity = {
    firstName: "Sarah",
    country: "Canada",
    occupation: "Technical Writer",
    hobbies: ["photography", "birdwatching", "baseball"],
    };
    const skills = ["HTML", "CSS", "JavaScript", "React", "Astro", "Writing Docs"];
    const happy = true;
    const finished = false;
    const goal = 3;
    ---
  2. Añade las siguientes líneas debajo de tus párrafos existentes.

    Luego, revisa la vista previa en vivo en tu pestaña del navegador para ver qué se muestra en la página:

    src/pages/about.astro
    {happy && <p>I am happy to be learning Astro!</p>}
    {finished && <p>I finished this tutorial!</p>}
    {goal === 3 ? <p>My goal is to finish in 3 days.</p> : <p>My goal is not 3 days.</p>}
  3. Haz commit de tus cambios a GitHub antes de continuar. Haz esto cada vez que quieras guardar tu trabajo y actualizar tu sitio web en vivo.

Dado el siguiente script .astro:

src/pages/about.astro
---
const operatingSystem = "Linux";
const quantity = 3;
const footwear = "boots";
const student = false;
---

Para cada expresión de plantilla de Astro, ¿puedes predecir el HTML (¡si lo hay!) que será enviado al navegador? Haz clic para revelar si estás en lo correcto!

  1. <p>{operatingSystem}</p>

  2. {student && <p>I am still in school.</p>}

  3. <p>I have {quantity + 8} pairs of {footwear}</p>

  4. {operatingSystem === "MacOS" ? <p>I am using a Mac.</p> : <p>I am not using a Mac.</p>}

Contribuir Comunidad Patrocinar