Components and layouts

Use template expressions

Insert values, choose markup, and render arrays with JavaScript expressions.

8 minute lesson

~~~

Use braces for expressions:

<h1>{title}</h1>
{featured && <strong>Featured</strong>}
<ul>
  {items.map(item => <li>{item.name}</li>)}
</ul>

The expressions run while Astro renders the template. They choose the resulting HTML; they do not keep watching values in the browser. If featured changes later in client-side code, this block will not rerender by itself.

Use normal JavaScript before the template for anything that would make the markup hard to read:

---
const visibleItems = items.filter(item => !item.draft)
---

{visibleItems.length > 0 ? (
  <ul>{visibleItems.map(item => <li>{item.name}</li>)}</ul>
) : (
  <p>No items yet.</p>
)}

Astro resembles JSX, but it follows HTML more closely: use class, and multiple top-level elements are allowed. Values inserted with {value} are escaped, which is the safe default for untrusted text. Treat any API that deliberately inserts raw HTML as a security-sensitive exception.

Render the page, then view its source. You should be able to connect each branch and loop to the static HTML it produced.

Lesson completed

Take this course offline

Get every free book and course as PDF and EPUB files.

Get the download library →