生成器

生成器根据处理过的文件构建路由。

¥A generator builds routes based on processed files.

概要

¥Synopsis

hexo.extend.generator.register(name, function (locals) {
// ...
});

locals 参数将传递到包含 站点变量 的函数中。你应该使用此参数获取网站数据,从而避免直接访问数据库。

¥A locals argument will get passed into the function, containing the site variables. You should use this argument to get the website data, thereby avoiding having to access the database directly.

更新路由

¥Update Routes

hexo.extend.generator.register("test", function (locals) {
// Object
return {
path: "foo",
data: "foo",
};

// Array
return [
{ path: "foo", data: "foo" },
{ path: "bar", data: "bar" },
];
});
属性 描述
path 不包括前缀 / 的路径。
data 数据
layout 布局。指定要渲染的布局。值可以是字符串或数组。如果忽略它,则路由将直接返回 data

当源文件更新时,Hexo 将执行所有生成器并重建路由。请返回数据,不要直接访问路由。

¥When the source files are updated, Hexo will execute all generators and rebuild the routes. Please return the data and do not access the router directly.

示例

¥Example

存档页面

¥Archive Page

archives/index.html 创建一个存档页面。我们将所有帖子作为数据传递给模板。此数据相当于模板中的 page 变量。

¥Create an archive page at archives/index.html. We pass all posts as data to the templates. This data is equivalent to the page variable in templates.

接下来,设置 layout 属性以使用主题模板进行渲染。我们在此示例中设置了两种布局:如果 archive 布局不存在,则将使用 index 布局。

¥Next, set the layout attribute to render with the theme templates. We’re setting two layouts in this example: if the archive layout doesn’t exist, the index layout will be used instead.

hexo.extend.generator.register("archive", function (locals) {
return {
path: "archives/index.html",
data: locals,
layout: ["archive", "index"],
};
});

带分页的存档页面

¥Archive Page with Pagination

你可以使用方便的官方工具 hexo-pagination 轻松构建带分页的存档页面。

¥You can use the convenient official tool hexo-pagination to easily build archive pages with pagination.

var pagination = require("hexo-pagination");

hexo.extend.generator.register("archive", function (locals) {
// hexo-pagination makes an index.html for the /archives route
return pagination("archives", locals.posts, {
perPage: 10,
layout: ["archive", "index"],
data: {},
});
});

生成所有帖子

¥Generate All Posts

遍历 locals.posts 中的所有帖子并为所有帖子创建路由。

¥Iterate over all posts in locals.posts and create routes for all the posts.

hexo.extend.generator.register("post", function (locals) {
return locals.posts.map(function (post) {
return {
path: post.path,
data: post,
layout: "post",
};
});
});

复制文件

¥Copy Files

这次我们不显式返回数据,而是将 data 设置为函数,这样路由仅在需要时构建 fs.ReadStream

¥This time we don’t return the data explicitly but instead set data to a function so the route will build fs.ReadStream only when needed.

var fs = require("hexo-fs");

hexo.extend.generator.register("asset", function (locals) {
return {
path: "file.txt",
data: function () {
return fs.createReadStream("path/to/file.txt");
},
};
});