Consider this Astro component code:
--- const greeting = 'Hello'; const name = 'World'; ---{greeting}, {name}!
What will this component render in the browser?
--- const greeting = 'Hello'; const name = 'World'; --- <h1>{greeting}, {name}!</h1>
Remember that variables inside curly braces in Astro templates are replaced by their values.
The frontmatter defines greeting and name. The template uses curly braces to insert their values, so the output is <h1>Hello, World!</h1>.
Astro components use frontmatter to write JavaScript or TypeScript code. Which of these is the correct syntax for frontmatter?
Astro uses triple dashes to mark frontmatter.
Astro frontmatter is enclosed between --- lines at the top of the file.
Look at this Astro component:
--- const message = 'Hi there!' const len = message.length ---{message}
It throws a syntax error. What is the cause?
--- const message = 'Hi there!' const len = message.length --- <p>{message}</p>
Check JavaScript syntax rules inside frontmatter.
In Astro frontmatter, JavaScript code must follow normal syntax rules. Missing semicolons can cause errors depending on the parser.
Consider this Astro component:
---
function greet(name) {
return `Hello, ${name}!`;
}
const user = 'Alice';
---
{greet(user)}
What will be rendered in the browser?
---
function greet(name) {
return `Hello, ${name}!`;
}
const user = 'Alice';
---
<h2>{greet(user)}</h2>Functions in frontmatter can be called inside templates with curly braces.
The function greet returns a string using the passed name. The template calls greet(user) which returns Hello, Alice!.
In Astro, what is the result of writing HTML tags inside the frontmatter section?
--- const title = 'Welcome
';{title}---
---
const title = '<h1>Welcome</h1>';
<div>{title}</div>
---Frontmatter is for JavaScript code only, not HTML markup.
Astro frontmatter must contain only JavaScript or TypeScript code. Writing HTML tags directly inside frontmatter causes a syntax error.
