2 • Add, style and link to pages on your site
Add dynamic content about you
Now that you have a multi-page website with HTML content, it’s time to add some dynamic HTML!
Get ready to…
- Define your page title in frontmatter, and use it in your HTML
- Conditionally display HTML elements
- Add some content about you
Any HTML file is valid Astro language. But, you can do more with Astro than just regular HTML!
Define and use a variable
Section titled Define and use a variableOpen about.astro
, which should look like this:
-
Add the following line of JavaScript in the frontmatter script, between the code fences:
-
Replace both the static “Astro” title and “About Me” heading in your HTML with the dynamic variable
{pageTitle}
. -
Refresh the live preview of your
/about
page.Your page text should look the same, and your page title displayed in your browser tab should now read “About Me” instead of “Astro.”
Instead of typing text directly into HTML tags, you just defined and then used a variable in the two sections of your
.astro
file, respectively. -
Use the same pattern to create a
pageTitle
value to use inindex.astro
(“Home Page”) andblog.astro
(“My Astro Learning Blog”). Update the HTML of these pages in both places so that your page title matches the heading displayed on each page.
Write JavaScript expressions in Astro
Section titled Write JavaScript expressions in Astro-
Add the following JavaScript to your frontmatter, between the code fences:
(You can customize the code for yourself, but this tutorial will use the following example.)
-
Then, add the following code to your HTML template, below your existing content:
Test your knowledge
Section titled Test your knowledge-
A
.astro
file’s frontmatter is written in: -
In addition to HTML, Astro syntax allows you to include:
-
When do you need to write your JavaScript inside curly braces?
Conditionally render elements
Section titled Conditionally render elementsYou can also use your script variables to choose whether or not to render individual elements of your HTML <body>
content.
-
Add the following lines to your frontmatter script to define variables:
-
Add the following lines below your existing paragraphs.
Then, check the live preview in your browser tab to see what is displayed on the page:
-
Commit your changes to GitHub before moving on. Do this any time you want to save your work and update your live website.
Analyze the Pattern
Section titled Analyze the PatternGiven the following .astro
script:
For each Astro template expression, can you predict the HTML (if any!) that will be sent to the browser? Click to reveal if you’re right!
-
<p>{operatingSystem}</p>
-
{student && <p>I am still in school.</p>}
-
<p>I have {quantity + 8} pairs of {footwear}</p>
-
{operatingSystem === "MacOS" ? <p>I am using a Mac.</p> : <p>I am not using a Mac.</p>}