如何在Astro中獲取當前頁鏈接

在Astro中,我們有時候會需要用到當前頁的地址,來做一些跳轉或者別的處理,Astro提供了一些有用的工具和全局變量,可以幫助我們實現這一目標。

使用 Astro.url.pathname

Astro提供了 Astro.url.pathname,一個全局對象,包含了當前請求的URL路徑。我們可以在頁面組件中使用它來獲取當前頁面的鏈接。例如:

1
---
2
import { Astro } from "astro";
3
const currentPath = Astro.url.pathname;
4
---
5
6
<!doctype html>
7
<html lang="en">
8
<head>
9
<meta charset="UTF-8" />
10
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
11
<title>My Astro Blog</title>
12
</head>
13
<body>
14
<h1>歡迎來到我的博客</h1>
15
<p>當前頁面鏈接: {currentPath}</p>
16
</body>
17
</html>

使用 Astro.request.url

另一種方法是使用 Astro.request.url 來獲取完整的當前頁面URL。這對於需要獲取完整URL的情況非常有用。例如:

1
---
2
import { Astro } from "astro";
3
const currentUrl = Astro.request.url;
4
---
5
6
<!doctype html>
7
<html lang="en">
8
<head>
9
<meta charset="UTF-8" />
10
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
11
<title>My Astro Blog</title>
12
</head>
13
<body>
14
<h1>歡迎來到我的博客</h1>
15
<p>當前頁面完整URL: {currentUrl}</p>
16
</body>
17
</html>

使用 Frontmatter 中的 slug

Astro為markdown生成的頁面提供了 slug 路徑信息,我們可以利用它來構建頁面鏈接。例如:

1
---
2
title: "我的博客文章"
3
---

在頁面組件中,我們可以這樣使用:

1
---
2
import { Astro } from "astro";
3
const { slug } = Astro.props;
4
const currentPath = `/posts/${slug}`;
5
---
6
7
<!doctype html>
8
<html lang="en">
9
<head>
10
<meta charset="UTF-8" />
11
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
12
<title>My Astro Blog</title>
13
</head>
14
<body>
15
<h1>歡迎來到我的博客</h1>
16
<p>當前頁面路徑: {currentPath}</p>
17
</body>
18
</html>

結論

我們可以根據自己的需要選擇不同的方法來獲取Astro中當前頁面的鏈接。無論是使用Astro提供的全局對象,還是利用Frontmatter中的信息,都可以幫助我們在生成的頁面中訪問當前的URL信息。