소개를 위한 동적 콘텐츠 추가
이제 HTML 콘텐츠가 포함된 여러 페이지로 구성된 웹사이트가 있으므로 동적 HTML을 추가할 차례입니다!
이번에 배울 내용
- 프런트매터에 페이지 제목을 정의하고 HTML에서 사용
- HTML 요소를 조건부로 표시
- 여러분에 관한 콘텐츠를 추가
모든 HTML 파일은 유효한 Astro 언어입니다. 하지만 Astro를 사용하면 일반 HTML보다 더 많은 일을 할 수 있습니다!
변수 정의 및 사용
다음과 같은 about.astro를 엽니다.
---
---
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width" />
<title>Astro</title>
</head>
<body>
<a href="/">Home</a>
<a href="/about/">About</a>
<a href="/blog/">Blog</a>
<h1>About Me</h1>
<h2>... and my new Astro site!</h2>
<p>I am working through Astro's introductory tutorial. This is the second page on my website, and it's the first one I built myself!</p>
<p>This site will update as I complete more of the tutorial, so keep checking back and see how my journey is going!</p>
</body>
</html>프런트매터 스크립트의 코드 펜스 사이에 다음 JavaScript 줄을 추가합니다.
--- const pageTitle = "About Me"; ---HTML의 정적 "Astro" 제목과 "About Me" 제목을 모두 동적 변수
{pageTitle}로 바꾸세요.<html lang="en"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width" /> <title>Astro</title> <title>{pageTitle}</title> </head> <body> <a href="/">Home</a> <a href="/about/">About</a> <a href="/blog/">Blog</a> <h1>About Me</h1> <h1>{pageTitle}</h1> <h2>... and my new Astro site!</h2> <p>I am working through Astro's introductory tutorial. This is the second page on my website, and it's the first one I built myself!</p> <p>This site will update as I complete more of the tutorial, so keep checking back and see how my journey is going!</p> </body> </html>/about페이지의 실시간 미리보기를 새로 고칩니다.페이지 텍스트는 동일하게 표시되어야 하며, 브라우저 탭에 표시되는 페이지 제목은 이제 "Astro" 대신 "About Me"로 표시되어야 합니다.
HTML 태그에 텍스트를 직접 입력하는 대신
.astro파일의 두 섹션에서 각각 변수를 정의한 후 사용했습니다.동일한 패턴을 사용하여
index.astro("홈 페이지") 및blog.astro("내 Astro 학습 블로그")에서 사용할pageTitle값을 만듭니다. 페이지 제목이 각 페이지에 표시되는 제목과 일치하도록 두 위치 모두에서 이 페이지의 HTML을 업데이트합니다.
:::note[핵심사항]
- JavaScript 또는 TypeScript 표현식을 사용하여 Astro 스크립트에서 변수를 정의하세요.
- Astro 템플릿에서 중괄호
{ }안에 이 변수를 사용하여 Astro에 JavaScript를 사용하고 있음을 알립니다.:::
Astro에서 JavaScript 표현식 작성
코드 펜스 사이에 있는 프런트매터에 다음 JavaScript를 추가하세요.
(코드를 직접 사용자 정의할 수 있지만 이 튜토리얼에서는 다음 예시를 사용합니다.)
--- const pageTitle = "About Me"; const identity = { firstName: "Sarah", country: "Canada", occupation: "Technical Writer", hobbies: ["photography", "birdwatching", "baseball"], }; const skills = ["HTML", "CSS", "JavaScript", "React", "Astro", "Writing Docs"]; ---그런 다음 HTML 템플릿의 기존 콘텐츠 아래에 다음 코드를 추가하세요.
<p>Here are a few facts about me:</p> <ul> <li>My name is {identity.firstName}.</li> <li>I live in {identity.country} and I work as a {identity.occupation}.</li> {identity.hobbies.length >= 2 && <li>Two of my hobbies are: {identity.hobbies[0]} and {identity.hobbies[1]}</li> } </ul> <p>My skills are:</p> <ul> {skills.map((skill) => <li>{skill}</li>)} </ul>
:::note[핵심사항]
- Astro 템플릿 작성은 HTML 작성과 매우 유사하지만 그 안에 JavaScript 표현식을 포함할 수 있습니다.
- Astro 프런트매터 스크립트에는 JavaScript만 포함되어 있습니다.
.astro파일의 어느 섹션에서나 모든 최신 JavaScript 논리 연산자, 표현식, 함수를 사용할 수 있습니다. 그러나 HTML 템플릿 본문에는 중괄호만 필요합니다.:::
지식을 테스트해보세요
.astro파일의 프런트매터는 다음과 같이 작성됩니다:HTML 외에도 Astro 구문을 사용하면 다음을 포함할 수 있습니다.
언제 중괄호 안에 JavaScript를 작성해야 합니까?
요소를 조건부로 렌더링
또한 스크립트 변수를 사용하여 HTML <body> 콘텐츠의 개별 요소를 렌더링할지 여부를 선택할 수도 있습니다.
변수를 정의하려면 프런트매터 스크립트에 다음 줄을 추가하세요.
--- const pageTitle = "About Me"; const identity = { firstName: "Sarah", country: "Canada", occupation: "Technical Writer", hobbies: ["photography", "birdwatching", "baseball"], }; const skills = ["HTML", "CSS", "JavaScript", "React", "Astro", "Writing Docs"]; 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>}계속 진행하기 전에 변경 사항을 GitHub에 커밋하세요. 작업을 저장하고 라이브 웹사이트를 업데이트하고 싶을 때 언제든지 이 작업을 수행하세요.
:::tipAstro의 템플릿 구문은 JSX 구문과 유사합니다. HTML에서 스크립트를 사용하는 방법이 궁금하다면 JSX에서 스크립트가 어떻게 수행되는지 검색하는 것이 아마도 좋은 출발점이 될 것입니다!:::
패턴 분석
다음 .astro 스크립트를 가정해 보겠습니다.
---
const operatingSystem = "Linux";
const quantity = 3;
const footwear = "boots";
const student = false;
---각 Astro 템플릿 표현식에 대해 브라우저로 전송될 HTML (있는 경우!)을 예측할 수 있습니까? 여러분이 옳았는지 확인하려면 클릭하세요!
<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>}