Bird
Raised Fist0
Astroframework~15 mins

Component structure (frontmatter + template) in Astro - Deep Dive

Choose your learning style10 modes available
Overview - Component structure (frontmatter + template)
What is it?
In Astro, a component is a reusable piece of a webpage made by combining two parts: frontmatter and template. The frontmatter is a special section at the top where you write JavaScript or TypeScript code to prepare data or logic. The template is the HTML-like part below that uses this data to show content on the page. Together, they let you build dynamic, organized web components easily.
Why it matters
Without a clear component structure, web pages become messy and hard to maintain. Astro's frontmatter and template separation helps keep code clean and organized, making it easier to build fast, scalable websites. This structure also allows you to mix logic and display in a simple way, improving developer productivity and reducing bugs.
Where it fits
Before learning this, you should understand basic HTML and JavaScript. After mastering component structure, you can explore advanced Astro features like server-side rendering, client hydration, and integrating other frameworks inside Astro components.
Mental Model
Core Idea
An Astro component splits logic (frontmatter) and display (template) so you can prepare data first, then show it clearly.
Think of it like...
It's like cooking a meal: first you prepare ingredients (frontmatter), then you plate the food beautifully (template) for serving.
┌─────────────────────────────┐
│ Astro Component             │
├───────────────┬─────────────┤
│ Frontmatter   │ Template    │
│ (JS/TS code)  │ (HTML view) │
│ Prepares data │ Shows data  │
└───────────────┴─────────────┘
Build-Up - 7 Steps
1
FoundationUnderstanding Astro Frontmatter Basics
🤔
Concept: Learn what frontmatter is and how to write JavaScript inside it.
Frontmatter is a special section at the top of an Astro component enclosed by triple dashes (---). Inside, you write JavaScript or TypeScript code to define variables, import modules, or run logic before rendering. For example: --- const greeting = 'Hello, world!'; ---
Result
You can define data or functions that the template can use later.
Knowing frontmatter lets you prepare everything your component needs before showing anything on the page.
2
FoundationWriting the Template Section
🤔
Concept: Learn how to write the HTML-like template that displays content using frontmatter data.
Below the frontmatter, you write the template using HTML syntax. You can insert JavaScript expressions inside curly braces {} to show dynamic content. For example: --- const greeting = 'Hello, world!'; ---

{greeting}

Result
The page will display a heading with the text 'Hello, world!'.
Separating display from logic helps keep your code clean and easy to read.
3
IntermediateUsing Imports and Variables in Frontmatter
🤔
Concept: Learn to import other modules and define variables in frontmatter for use in the template.
You can import JavaScript modules or components inside frontmatter to reuse code. For example: --- import { formatDate } from '../utils/date.js'; const today = formatDate(new Date()); ---

Today is {today}

Result
The template shows the formatted current date inside a paragraph.
Frontmatter acts like a setup area where you gather all data and tools your template needs.
4
IntermediateEmbedding Expressions and Conditionals in Template
🤔Before reading on: do you think you can use JavaScript if statements directly inside the template HTML? Commit to yes or no.
Concept: Learn how to use JavaScript expressions and conditionals inside the template to control what is shown.
You can embed JavaScript expressions inside curly braces {} in the template. For conditionals, you use JavaScript ternary operators or logical && inside the template. For example: --- const isLoggedIn = true; ---

{isLoggedIn ? 'Welcome back!' : 'Please log in.'}

Result
The paragraph shows 'Welcome back!' if isLoggedIn is true, otherwise 'Please log in.'.
Knowing how to embed logic in the template lets you create dynamic views without mixing too much code.
5
IntermediatePassing Props to Components
🤔Before reading on: do you think frontmatter can receive data from outside the component? Commit to yes or no.
Concept: Learn how Astro components receive data (props) and use them in frontmatter and template.
Astro components can accept data from their parent using props. You declare props by exporting variables in frontmatter. For example: --- export let name = 'Guest'; ---

Hello, {name}!

Result
The component shows a greeting with the passed name or 'Guest' if none is given.
Understanding props lets you build reusable components that change based on input.
6
AdvancedCombining Frontmatter with Client-Side Scripts
🤔Before reading on: do you think frontmatter code runs in the browser or only during build? Commit to your answer.
Concept: Learn the difference between frontmatter code running at build time and client-side scripts running in the browser.
Frontmatter code runs only once during build or server rendering, not in the browser. To add interactivity, you include client-side scripts inside the template using
Root cause:Misunderstanding that frontmatter is static and does not run in the browser, so variables there cannot update dynamically.
#2Writing multiple frontmatter blocks in one component.
Wrong approach:--- const a = 1; ---
{a}
--- const b = 2; ---

{b}

Correct approach:--- const a = 1; const b = 2; ---
{a}

{b}

Root cause:Not knowing frontmatter must be a single block at the top of the file.
#3Using full JavaScript statements like if or for directly in template HTML.
Wrong approach:--- const items = [1,2,3]; ---
    {for (const item of items) {
  • {item}
  • }}
Correct approach:--- const items = [1,2,3]; ---
    {items.map(item =>
  • {item}
  • )}
Root cause:Confusing template expressions with full JavaScript syntax; templates only accept expressions.
Key Takeaways
Astro components have two parts: frontmatter for logic and template for display, keeping code organized.
Frontmatter runs once at build or server render time and does not run in the browser, so it cannot handle dynamic UI updates.
Templates use expressions to show data prepared in frontmatter, but cannot contain full JavaScript statements.
Props are passed into components via exported variables in frontmatter, enabling reusable and customizable components.
Understanding the static nature of frontmatter helps balance performance and interactivity by adding client-side scripts only when needed.

Practice

(1/5)
1. What is the purpose of the frontmatter section in an Astro component?
easy
A. To style the component with CSS
B. To write JavaScript code and define variables used in the template
C. To write HTML markup for the component
D. To import other components only

Solution

  1. Step 1: Understand frontmatter role

    The frontmatter section is where you write JavaScript code, such as variables or functions, that the template can use.
  2. Step 2: Differentiate from template

    The template part is for HTML markup, not code. Styling is done separately, not in frontmatter.
  3. Final Answer:

    To write JavaScript code and define variables used in the template -> Option B
  4. Quick Check:

    Frontmatter = JavaScript code [OK]
Hint: Frontmatter holds code; template holds HTML display [OK]
Common Mistakes:
  • Confusing frontmatter with template HTML
  • Thinking frontmatter is for CSS styling
  • Believing frontmatter is only for imports
2. Which of the following is the correct way to start the frontmatter section in an Astro component?
easy
A. //
B. { }
C. /* */
D. ---

Solution

  1. Step 1: Identify frontmatter syntax

    Astro uses triple dashes --- at the top and bottom to mark the frontmatter section.
  2. Step 2: Compare options

    Curly braces, comments, or single slashes are not used to mark frontmatter.
  3. Final Answer:

    --- -> Option D
  4. Quick Check:

    Frontmatter starts with --- [OK]
Hint: Frontmatter always starts and ends with --- [OK]
Common Mistakes:
  • Using curly braces to start frontmatter
  • Confusing comments with frontmatter markers
  • Omitting the closing ---
3. Given this Astro component code, what will be displayed when rendered?
---
const greeting = "Hello, Astro!";
---

{greeting}

medium
A.

{greeting}

B.

C.

Hello, Astro!

D. Error: greeting is undefined

Solution

  1. Step 1: Understand variable usage

    The variable greeting is defined in frontmatter with value "Hello, Astro!".
  2. Step 2: Template interpolation

    The template uses curly braces {greeting} to insert the variable's value into the HTML.
  3. Final Answer:

    <h1>Hello, Astro!</h1> -> Option C
  4. Quick Check:

    Curly braces insert variable value [OK]
Hint: Curly braces show frontmatter variables in template [OK]
Common Mistakes:
  • Thinking curly braces show as text literally
  • Assuming variable is undefined without frontmatter
  • Forgetting to close frontmatter with ---
4. What is wrong with this Astro component code?
---
const name = "Astro";

Hello, {name}!

---
medium
A. The template HTML is inside the frontmatter section
B. The variable name is not defined
C. Curly braces cannot be used in Astro templates
D. Missing closing tag for <h1>

Solution

  1. Step 1: Identify frontmatter boundaries

    Frontmatter is only for JavaScript code and must be enclosed between --- lines.
  2. Step 2: Check template placement

    The HTML template must be outside the frontmatter. Here, the <h1> is inside frontmatter, causing an error.
  3. Final Answer:

    The template HTML is inside the frontmatter section -> Option A
  4. Quick Check:

    Template must be outside frontmatter [OK]
Hint: Keep HTML outside --- frontmatter --- [OK]
Common Mistakes:
  • Placing HTML inside frontmatter
  • Forgetting to close frontmatter with ---
  • Misusing curly braces syntax
5. How can you display a list of items defined in frontmatter inside the template in Astro? Choose the correct code snippet to render a list of fruits stored in fruits array.
hard
A.
---
const fruits = ["Apple", "Banana", "Cherry"];
---
    {fruits.map(fruit =>
  • {fruit}
  • )}
B.
---
const fruits = ["Apple", "Banana", "Cherry"];
---
    {for fruit in fruits}
  • {fruit}
  • {/for}
C.
---
const fruits = ["Apple", "Banana", "Cherry"];
---
    {fruits.forEach(fruit =>
  • {fruit}
  • )}
D.
---
const fruits = ["Apple", "Banana", "Cherry"];
---
    {fruits.map(fruit => "
  • " + fruit + "
  • ")}

Solution

  1. Step 1: Understand how to loop in Astro template

    Astro templates use JavaScript expressions inside curly braces. map() returns an array of JSX elements to render.
  2. Step 2: Check each option's correctness

    ---
    const fruits = ["Apple", "Banana", "Cherry"];
    ---
    
      {fruits.map(fruit =>
    • {fruit}
    • )}
    uses map() correctly to return <li> elements.
    ---
    const fruits = ["Apple", "Banana", "Cherry"];
    ---
    
      {for fruit in fruits}
    • {fruit}
    • {/for}
    uses invalid syntax.
    ---
    const fruits = ["Apple", "Banana", "Cherry"];
    ---
    
      {fruits.forEach(fruit =>
    • {fruit}
    • )}
    uses forEach() which returns undefined.
    ---
    const fruits = ["Apple", "Banana", "Cherry"];
    ---
    
      {fruits.map(fruit => "
    • " + fruit + "
    • ")}
    returns strings, not JSX elements.
  3. Final Answer:

    Option A correctly renders the list using map() -> Option A
  4. Quick Check:

    Use map() to render lists in Astro templates [OK]
Hint: Use map() inside curly braces to render lists [OK]
Common Mistakes:
  • Using forEach instead of map for rendering
  • Trying template loops with invalid syntax
  • Returning strings instead of JSX elements
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard