Skip to content
Tutorials Center
My learning

Topics

Lesson 3 of 37 ยท Getting Started

Anatomy of an Astro Component

Learn the .astro file format: the frontmatter fence, template expressions, conditionals, loops, fragments, HTML attributes and comments.

Every page, layout and component in Astro is an .astro file, so understanding its structure is the most important skill in this course. An .astro component has two zones: a component script at the top (between two --- lines) and a component template below. The script prepares data; the template describes the HTML.

If you know HTML and a little JavaScript, you already know most of it. The template is HTML with in curly braces, similar to JSX but with some friendlier rules, such as using the real HTML attribute names class and for.

The two zones

ASTRO
---
// Component script: runs on the server, once per render.
const name = "Ada";
const year = new Date().getFullYear();
---
<!-- Component template: HTML plus expressions. -->
<footer>
  <p>Built by {name} in {year}</p>
</footer>

Key facts:

  • The script always runs on the server (during the build, or per request in SSR). It never runs in the browser.
  • You can import components and data, use top-level await, call fetch, read files and talk to a database here.
  • Variables declared in the script are available in the template.
  • The fence is optional. A component with no logic can be plain HTML.

Because the fence code is not shipped to the browser, secrets such as API keys are safe in it as long as you do not print them into the template.

Expressions

Anything inside { } in the template is a JavaScript expression:

ASTRO
---
const price = 19.5;
const tax = 0.2;
---
<p>Total: {(price * (1 + tax)).toFixed(2)}</p>
<p>{price > 10 ? "Free shipping" : "Shipping applies"}</p>

Expressions also work inside attribute values, with no quotes around the braces:

ASTRO
---
const url = "https://example.com";
const label = "Docs";
---
<a href={url} title={`Open ${label}`}>{label}</a>

Conditionals and loops

There is no special if or for tag. You use ordinary JavaScript expressions. Use && or a ternary for conditionals, and .map() for lists:

ASTRO
---
const user = { name: "Mina", admin: true };
const tags = ["css", "html", "astro"];
---
{user.admin && <span class="badge">Admin</span>}

<ul>
  {tags.map((tag) => (
    <li>{tag}</li>
  ))}
</ul>

Remember to give lists that you build from data one root element per item. Unlike React, Astro does not need key props because it renders to a string once.

Fragments and multiple roots

A component can return several top-level elements without a wrapper. When you need to group elements inside an expression, use a fragment, written <>...</> or <Fragment>:

ASTRO
---
const items = ["one", "two"];
---
{items.map((x) => (
  <>
    <dt>{x}</dt>
    <dd>Description of {x}</dd>
  </>
))}

Raw HTML and escaping

Text values are escaped automatically, so user input cannot inject markup. If you truly have trusted HTML, use the set:html directive:

ASTRO
---
const trusted = "<strong>bold</strong>";
---
<p>{trusted}</p>             <!-- shows the tags as text -->
<p set:html={trusted} />     <!-- renders bold text -->

Never use set:html with content you did not write or sanitize.

Attributes that differ from React

  • Use class, not className, and for, not htmlFor.
  • class:list builds a class string from strings, arrays and objects.
  • style can take an object: style={{ color: "red" }} is converted to CSS text.
  • Boolean attributes work as expected: disabled={false} removes the attribute.
  • define:vars passes frontmatter values into a <style> or <script>, which later lessons cover.

Stand-in: splitting and rendering an .astro file

The real compiler is sophisticated, but the core idea is small: split the file at the fence, evaluate the script to get variables, then fill the template. This stand-in does exactly that for simple expressions.

Node.js Stand-in: a miniature .astro renderer

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Real Astro compiles the template to JavaScript functions rather than evaluating strings at runtime, and it escapes output. The sketch above shows the two-zone design, nothing more.

Stand-in: escaping versus set:html

Automatic escaping is one of the best safety features of a template language. This stand-in shows the difference.

Node.js Stand-in: escaped text versus raw HTML

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Components inside components

To use another component, import it in the fence and write it as a tag. Component names must start with a capital letter so they are not confused with HTML elements:

ASTRO
---
import Card from "../components/Card.astro";
---
<Card />

The next chapters cover passing data to components with props and slots; see Props and slots.

Comments

HTML comments <!-- --> in the template are included in the output. Use JavaScript comments in the fence, or put one in an expression, when you do not want a comment sent to the visitor:

ASTRO
{/* This comment is removed from the output */}

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What separates the component script from the template in an .astro file?

    The component script sits between two --- lines (the frontmatter fence). The template follows it.
  2. 2. How do you render a list from an array in the template?

    Templates are JavaScript expressions, so you use map() and return elements.
  3. 3. What does {userText} do with the characters < and > in the string?

    Expressions are escaped automatically. Use set:html only for trusted markup.
  4. 4. Which attribute name is correct in an .astro template?

    Astro uses real HTML attribute names, so class and for rather than className and htmlFor.

Summary

  • An .astro file is a server-only component script plus an HTML-like template.
  • Curly braces hold JavaScript expressions, including inside attributes.
  • Use ternaries, && and .map() for conditions and loops; fragments group elements without a wrapper.
  • Output is escaped by default; set:html renders raw HTML and must be used carefully.
  • Components are imported in the fence and used as capitalized tags.

Next: The CLI and Configuration