`&&`, Ternary, or Compute in the Frontmatter
Conditionals
Astro inherits JSX's three patterns for conditional rendering — plus the option to do the branching in the frontmatter and just drop a value.
What you'll learn
- Use `&&`, ternary, and frontmatter branching
- Recognize what renders as nothing
Astro has no {#if} block (Svelte) or v-if (Vue). Use plain
JavaScript inside { ... }.
&& — Show Or Don’t
{count > 0 && <span class="badge">{count}</span>} Ternary — This or That
<p>{user ? `Hi, ${user.name}` : "Hi, stranger"}</p> Compute in Frontmatter
For anything more than a quick check, branch in the frontmatter:
---
const { status } = Astro.props;
let label = "Pending";
let badgeClass = "warn";
if (status === "ok") { label = "Done"; badgeClass = "good"; }
if (status === "error") { label = "Failed"; badgeClass = "bad"; }
---
<span class:list={["badge", `badge--${badgeClass}`]}>{label}</span> The template stays clean; all the branching is up top where it can be a normal block of code.
Many Branches — Object Lookup
---
const { status } = Astro.props;
const labels = { ok: "Done", error: "Failed", pending: "Pending" };
const label = labels[status] ?? status;
---
<span>{label}</span> What Renders As Nothing
Same as JSX — null, undefined, false, true all produce no
output. That’s why {cond && <X />} is a “show only when” pattern.
Up Next
The other half of dynamic UI — rendering arrays.
Lists →