ジェネレータ

ジェネレータは、処理されたファイルに基づいてルートを構築します。

概要

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

関数にはlocals引数が渡され、サイト変数が含まれます。ウェブサイトデータが必要な場合、直接データベースにアクセスするのを避け、この引数を利用してください。

ルートの更新

hexo.extend.generator.register('test', function(locals){
// オブジェクト
return {
path: 'foo',
data: 'foo'
};

// 配列
return [
{path: 'foo', data: 'foo'},
{path: 'bar', data: 'bar'}
];
});
属性 説明
path 先頭の/を含まないパス。
data データ
layout レイアウト。レンダリングに使用するレイアウトを文字列または配列で指定します。無指定の場合、ルートはdataを直接返します。

ソースファイルが更新されると、Hexoはすべてのジェネレータを実行し、ルートを再構築します。ここではあくまでデータを返し、直接ルーターにアクセスしないでください。

アーカイブページ

archives/index.htmlにアーカイブページを作成します。テンプレートにすべての記事をデータとして渡します。このデータはテンプレート内のpage変数と同等です。

次に、layout属性を設定してテーマテンプレートでレンダリングします。この例では2つのレイアウトを設定しています。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は/archivesルートにindex.htmlを作成します
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'
};
});
});

ファイルのコピー

この例ではデータを明示的に返さず、ルートが必要なときにのみfs.ReadStreamを生成する関数をdataに設定しています。

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')
}
};
});