#How to do an if block in an astro file?
1 messages · Page 1 of 1 (latest)
In Astro, you can use JavaScript logical operators and ternary expressions to create conditional (if) blocks within your Astro components. Here's an example:
---const visible = true;---
{visible && <p>Show me!</p>}
{visible ? <p>Show me!</p> : <p>Else show me!</p>}
In the example above, the first line visible && <p>Show me!</p> will only render the paragraph element if visible is true. The second line uses a ternary operator to conditionally render one of two paragraph elements based on the value of visible.
You can also use variables defined in the frontmatter script of your Astro file to conditionally render elements. Here's an example:
---const happy = true;const finished = false;const goal = 3;---
{happy && <p>I am happy to be learning Astro!</p>}
{finished && <p>I finished this tutorial!</p>}
{goal === 3 ? <p>My goal is to finish in 3 days.</p> : <p>My goal is not 3 days.</p>}
In this example, different paragraphs will be rendered based on the values of happy, finished, and goal.