创建多个页面
生成器允许从唯一的源文件创建多个页面
Lume 允许从同一个源文件生成多个页面。这对于使用外部源(如数据库或 API)以编程方式生成页面非常有用。
基础示例
要生成页面,源文件必须返回一个 生成器函数。生成器产生的每个元素都是一个新页面,并且必须至少包含 url
属性。
export default function* () {
yield {
url: "/page-1/",
content: "This is the first page",
};
yield {
url: "/page-2/",
content: "This is the second page",
};
yield {
url: "/page-3/",
content: "This is the third page",
};
}
在上面的例子中,此页面生成了三个页面。重要的是页面的 URL 必须是唯一的。
具有布局的多个页面
每个页面都是一个包含页面数据的对象。在前面的示例中,每个页面都有 url
和 content
属性,用于定义每个页面的内容和 URL。 如果你想使用布局来生成页面内容,你必须导出带有布局名称的 layout
关键字以及将在布局中使用的数据:
export default function* () {
yield {
url: "/page-1/",
layout: "layouts/article.vto",
title: "Article 1",
body: "Welcome to the article 1",
};
yield {
url: "/page-2/",
layout: "layouts/article.vto",
title: "Article 2",
body: "Welcome to the article 2",
};
yield {
url: "/page-3/",
layout: "layouts/article.vto",
title: "Article 3",
body: "Welcome to the article 3",
};
}
---
layout: layouts/base.vto
---
<article>
<h1>{{ title }}</h1>
<div>
{{ body |> md }}
</div>
</article>
由于所有页面的布局都相同,我们可以使用命名导出只定义一次,而不是在每个 yield 的页面中重复定义:
export const layout = "layouts/article.vto";
export default function* () {
yield {
url: "/page-1/",
title: "Article 1",
body: "Welcome to the article 1",
};
yield {
url: "/page-2/",
title: "Article 2",
body: "Welcome to the article 2",
};
yield {
url: "/page-3/",
title: "Article 3",
body: "Welcome to the article 3",
};
}
---
layout: layouts/base.vto
---
<article>
<h1>{{ title }}</h1>
<div>
{{ body |> md }}
</div>
</article>
从其他来源生成页面
使用生成器生成页面的这个简单概念非常灵活,可以用于许多用例。 例如,我们可以从数据库或 API 生成页面:
import database from "./my-database.ts";
export const layout = "layouts/article.vto";
export default function* () {
const articles = database.query("select * from articles");
for (const article of articles) {
yield {
url: `/articles/${article.slug}/`,
...article,
};
}
}
在这个例子中,我们使用数据库获取所有文章,并使用生成器为每篇文章生成一个新页面。 每个 yield 的文章都包含 URL 和您喜欢的其他属性(标题、类别、标签、正文等)。 我们正在导出 layout
值,以便所有页面都使用相同的布局进行渲染。
另一个常见的用例是分页。 请转到 搜索和分页 获取更多信息。