產生器

產生器會根據處理過後的檔案建立路由。

概要

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

一個 locals 參數將會被傳遞到函式中,包含網站變數。 您應該使用此參數來取得網站資料,從而避免直接存取資料庫。

更新路由

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 將執行所有產生器並重建路由。請回傳資料,不要直接存取路由器。

範例

封存頁面

archives/index.html 建立一個封存頁面。我們將所有文章作為資料傳遞給樣板。此資料等同於樣板中的 page 變數。

接下來,設定 layout 屬性以使用主題樣板進行渲染。在此範例中,我們設定了兩個版面配置:如果 archive 版面配置不存在,則會改用 index 版面配置。

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

使用分頁的封存頁面

您可以使用方便的官方工具 hexo-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: {},
});
});

產生所有文章

遍歷 locals.posts 中的所有文章,並為所有文章建立路由。

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

複製檔案

這次我們不顯式回傳資料,而是將 data 設定為函式,以便路由僅在需要時才建立 fs.ReadStream

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");
},
};
});