0
0
AstroHow-ToBeginner ยท 3 min read

How to Use Expressions in Astro: Simple Syntax and Examples

In Astro, you use expressions by wrapping JavaScript code inside { } within your component templates. These expressions can output dynamic content or run simple logic directly in your HTML markup.
๐Ÿ“

Syntax

Astro expressions use curly braces { } to embed JavaScript inside your HTML. Anything inside the braces is treated as JavaScript and its result is rendered.

You can use variables, function calls, or any valid JavaScript expression inside the braces.

astro
<div>
  <p>Hello, {name}!</p>
  <p>2 + 3 = {2 + 3}</p>
</div>
Output
<div> <p>Hello, Alice!</p> <p>2 + 3 = 5</p> </div>
๐Ÿ’ป

Example

This example shows how to use expressions to display a variable and a computed value inside an Astro component.

astro
---
const name = 'Alice';
const items = ['apple', 'banana', 'cherry'];
---
<html lang="en">
  <body>
    <h1>Hello, {name}!</h1>
    <p>You have {items.length} items:</p>
    <ul>
      {items.map(item => <li>{item}</li>)}
    </ul>
  </body>
</html>
Output
<html lang="en"> <body> <h1>Hello, Alice!</h1> <p>You have 3 items:</p> <ul> <li>apple</li> <li>banana</li> <li>cherry</li> </ul> </body> </html>
โš ๏ธ

Common Pitfalls

One common mistake is forgetting to wrap JavaScript expressions in { }, which causes Astro to treat them as plain text.

Another is trying to use statements like if directly inside expressions; Astro expressions only accept expressions, not statements.

Use ternary operators or conditional rendering blocks instead.

astro
---
const show = true;
---
<!-- Wrong: if statement inside braces -->
<p>{show ? 'Visible' : 'Hidden'}</p>

<!-- Right: use ternary expression -->
<p>{show ? 'Visible' : 'Hidden'}</p>
Output
<p>Visible</p>
๐Ÿ“Š

Quick Reference

  • Use { } to embed JavaScript expressions in Astro templates.
  • Expressions can be variables, calculations, or function calls.
  • Use ternary operators for conditional rendering inside expressions.
  • For loops, use array methods like map() inside expressions.
โœ…

Key Takeaways

Wrap JavaScript code inside { } to use expressions in Astro templates.
Expressions can output variables, calculations, or call functions directly.
Use ternary operators for conditions; statements like if cannot be used inside expressions.
Use array methods like map() inside expressions to render lists dynamically.
Always test expressions to ensure they return valid renderable content.