添加有关你的动态内容
现在你已经有了一个包含 HTML 内容的多页面网站,是时候添加一些动态 HTML 了!
¥Now that you have a multi-page website with HTML content, it’s time to add some dynamic HTML!
准备好……
-
在 frontmatter 中定义页面标题,并在 HTML 中使用它
-
有条件地显示 HTML 元素
-
添加一些关于你的内容
任何 HTML 文件都是有效的 Astro 语言。但是,你可以使用 Astro 做更多事情,而不仅仅是常规 HTML!
¥Any HTML file is valid Astro language. But, you can do more with Astro than just regular HTML!
定义和使用变量
标题部分 定义和使用变量¥Define and use a variable
打开 about.astro
,它应该如下所示:
¥Open 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.
在 Astro 中编写 JavaScript 表达式
标题部分 在 Astro 中编写 JavaScript 表达式¥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
.astro
文件的 frontmatter 写入:
- 除了 HTML 之外,Astro 语法还允许你包含:
- 什么时候需要在大括号内编写 JavaScript?
有条件地渲染元素
标题部分 有条件地渲染元素¥Conditionally render elements
你还可以使用脚本变量来选择是否渲染 HTML <body>
内容的各个元素。
¥You 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
给定以下 .astro
脚本:
¥Given the following .astro
script:
对于每个 Astro 模板表达式,你能否预测将发送到浏览器的 HTML(如果有!)?点击来揭晓你是否正确!
¥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>}
清单
标题部分 清单¥Checklist
资源
标题部分 资源¥Resources
Tutorials