EmDash 提供查询函数,用于在 Astro 页面和组件中检索内容。这些函数遵循 Astro 的 Live Content Collections 模式,返回带有错误处理的结构化结果。
查询函数
| 函数 | 用途 | 返回值 |
|---|---|---|
getEmDashCollection | 检索内容类型的所有条目 | { entries, error } |
getEmDashEntry | 按 ID 或 slug 检索单个条目 | { entry, error, isPreview } |
import { getEmDashCollection, getEmDashEntry } from "emdash";
获取所有条目
---
import { getEmDashCollection } from "emdash";
const { entries: posts, error } = await getEmDashCollection("posts");
if (error) {
console.error("加载文章失败:", error);
}
---
<ul>
{posts.map((post) => (
<li>{post.data.title}</li>
))}
</ul>
按区域设置过滤
当 i18n 已启用时,按区域设置过滤以检索特定语言的内容:
const { entries: frenchPosts } = await getEmDashCollection("posts", {
locale: "fr",
status: "published",
});
const { entries: localizedPosts } = await getEmDashCollection("posts", {
locale: Astro.currentLocale,
status: "published",
});
对于单个条目,将 locale 作为第三个参数传递:
const { entry: post } = await getEmDashEntry("posts", "my-post", {
locale: Astro.currentLocale,
});
省略 locale 时,默认使用请求的当前区域设置。如果请求的区域设置不存在翻译,则遵循回退链。
按状态过滤
const { entries: published } = await getEmDashCollection("posts", {
status: "published",
});
const { entries: drafts } = await getEmDashCollection("posts", {
status: "draft",
});
限制结果
const { entries: recentPosts } = await getEmDashCollection("posts", {
status: "published",
limit: 5,
});
按分类法过滤
const { entries: newsPosts } = await getEmDashCollection("posts", {
status: "published",
where: { category: "news" },
});
const { entries: jsPosts } = await getEmDashCollection("posts", {
status: "published",
where: { tag: "javascript" },
});
const { entries: featuredNews } = await getEmDashCollection("posts", {
status: "published",
where: { category: ["news", "featured"] },
});
当为单个分类法提供多个值时,where 过滤器使用 OR 逻辑。
错误处理
const { entries: posts, error } = await getEmDashCollection("posts");
if (error) {
console.error("加载文章失败:", error);
return new Response("服务器错误", { status: 500 });
}
获取单个条目
---
import { getEmDashEntry } from "emdash";
import { PortableText } from "emdash/ui";
const { slug } = Astro.params;
const { entry: post, error } = await getEmDashEntry("posts", slug);
if (error) {
return new Response("服务器错误", { status: 500 });
}
if (!post) {
return Astro.redirect("/404");
}
---
<article>
<h1>{post.data.title}</h1>
<PortableText value={post.data.content} />
</article>
条目返回类型
interface EntryResult<T> {
entry: ContentEntry<T> | null;
error?: Error;
isPreview: boolean;
}
interface ContentEntry<T> {
id: string;
data: T;
edit: EditProxy;
}
渲染 SEO 面板数据
对于具有 supports: ["seo"] 的集合,编辑人员可以在管理后台的 SEO 面板中设置 SEO 标题、元描述、OG 图片、规范 URL 和”对搜索引擎隐藏”(noindex) 开关。这些数据作为 entry.data.seo 传递。使用 getSeoMeta 将面板字段转换为可渲染的元标签:
---
import { getEmDashEntry, getSeoMeta } from "emdash";
const { entry, error } = await getEmDashEntry("posts", Astro.params.slug);
if (error) {
return new Response("服务器错误", { status: 500 });
}
if (!entry) return Astro.redirect("/404");
const seo = getSeoMeta(entry, {
siteTitle: "我的网站",
siteUrl: "https://example.com",
path: Astro.url.pathname,
});
---
<head>
<title>{seo.title}</title>
{seo.description && <meta name="description" content={seo.description} />}
{seo.ogImage && <meta property="og:image" content={seo.ogImage} />}
{seo.canonical && <link rel="canonical" href={seo.canonical} />}
{seo.robots && <meta name="robots" content={seo.robots} />}
</head>
预览模式
EmDash 通过中间件自动处理预览:
---
import { getEmDashEntry } from "emdash";
const { slug } = Astro.params;
const { entry, isPreview, error } = await getEmDashEntry("posts", slug);
if (error) {
return new Response("服务器错误", { status: 500 });
}
if (!entry) {
return Astro.redirect("/404");
}
---
{isPreview && (
<div class="preview-banner">
正在查看预览。此内容尚未发布。
</div>
)}
<article>
<h1>{entry.data.title}</h1>
<PortableText value={entry.data.content} />
</article>
可视化编辑
<article {...entry.edit}>
<h1 {...entry.edit.title}>{entry.data.title}</h1>
<div {...entry.edit.content}>
<PortableText value={entry.data.content} />
</div>
</article>
在编辑模式下,{...entry.edit.title} 会生成 data-emdash-ref 属性。在生产环境中不会产生输出。
内联代码块样式
| 属性 | 用途 |
|---|---|
--emdash-inline-code-background | 代码块背景 |
--emdash-inline-code-foreground | 普通代码文本 |
--emdash-inline-code-muted | 注释和引用文本 |
--emdash-inline-code-keyword | 关键字、字面量、选择器和删除文本 |
--emdash-inline-code-string | 字符串、属性、符号和添加文本 |
--emdash-inline-code-number | 数字和元数据 |
--emdash-inline-code-title | 标题、名称、类型和内置函数 |
--emdash-inline-code-border | 语言选择器边框 |
--emdash-inline-code-control-background | 语言选择器背景 |
--emdash-inline-code-control-foreground | 语言选择器文本和图标 |
--emdash-inline-code-focus | 键盘焦点指示器 |
:root {
--emdash-inline-code-background: #f7f7f5;
--emdash-inline-code-foreground: #24292f;
--emdash-inline-code-muted: #57606a;
--emdash-inline-code-keyword: #b8172a;
--emdash-inline-code-string: #0a3069;
--emdash-inline-code-number: #0550ae;
--emdash-inline-code-title: #7545c7;
--emdash-inline-code-border: #7d8590;
--emdash-inline-code-control-background: #fff;
--emdash-inline-code-control-foreground: #24292f;
--emdash-inline-code-focus: #0550ae;
}
:root.dark {
--emdash-inline-code-background: #202020;
--emdash-inline-code-foreground: #f0f3f6;
--emdash-inline-code-muted: #c9d1d9;
--emdash-inline-code-keyword: #ffc1bb;
--emdash-inline-code-string: #b9ddff;
--emdash-inline-code-number: #a8d5ff;
--emdash-inline-code-title: #e5ccff;
--emdash-inline-code-border: #6e7681;
--emdash-inline-code-control-background: #161b22;
--emdash-inline-code-control-foreground: #f0f3f6;
--emdash-inline-code-focus: #a8d5ff;
}
排序结果
const { entries: posts } = await getEmDashCollection("posts", { status: "published" });
const sorted = posts.sort(
(a, b) => (b.data.publishedAt?.getTime() ?? 0) - (a.data.publishedAt?.getTime() ?? 0),
);
常见排序模式
posts.sort((a, b) => a.data.title.localeCompare(b.data.title));
posts.sort((a, b) => (a.data.order ?? 0) - (b.data.order ?? 0));
posts.sort(() => Math.random() - 0.5);
TypeScript 类型
npx emdash types
import { getEmDashCollection, getEmDashEntry } from "emdash";
import type { Post } from "../.emdash/types";
const { entries: posts } = await getEmDashCollection<Post>("posts");
const { entry: post } = await getEmDashEntry<Post>("posts", "my-post");
静态 vs. 服务器渲染
静态(预渲染)
---
import { getEmDashCollection, getEmDashEntry } from "emdash";
export async function getStaticPaths() {
const { entries: posts } = await getEmDashCollection("posts", {
status: "published",
});
return posts.map((post) => ({ params: { slug: post.data.slug } }));
}
const { slug } = Astro.params;
const { entry: post } = await getEmDashEntry("posts", slug);
---
服务器渲染
---
export const prerender = false;
import { getEmDashEntry } from "emdash";
const { slug } = Astro.params;
const { entry: post, error } = await getEmDashEntry("posts", slug);
if (error) return new Response("服务器错误", { status: 500 });
if (!post) return new Response(null, { status: 404 });
---
性能考虑
缓存
---
const { entries: posts } = await getEmDashCollection("posts", { status: "published" });
Astro.response.headers.set("Cache-Control", "public, max-age=300");
---
避免冗余查询
---
import { getEmDashCollection } from "emdash";
import PostList from "../components/PostList.astro";
import Sidebar from "../components/Sidebar.astro";
const { entries: posts } = await getEmDashCollection("posts", { status: "published" });
const featured = posts.filter((p) => p.data.featured);
const recent = posts.slice(0, 5);
---
<PostList posts={featured} />
<Sidebar posts={recent} />