說明
- 腳本可以實現(xiàn)所有插件可以實現(xiàn)的功能
- npm插件是分享給大家用的小腳本而已
- 腳本需要掌握hexo api 地址在此
調(diào)用
腳本(Scripts)
只需要把 JavaScript 文件放到 scripts 文件夾,在啟動時就會自動載入。
最簡單用法
比如我們寫一個hello.js,放到scripts下,我們利用hexo.extend.helper輔助函數(shù)來寫點兒東西
hexo.extend.helper.register('js', function(path){
return '<script type="text/javascript" src="' + path + '"></script>';
});
在index.html模板中調(diào)用
<%- js('script-demo.js') %>
// <script type="text/javascript" src="script-demo.js"></script>
其實就是函數(shù)調(diào)用,很方便 很實用。
生成器(Generator) 詳解
第一個小例子
第一步
讓我們再創(chuàng)建一個js文件
/scripts/hello2.js
hexo.extend.generator.register('gen', function(locals){
return {
path: 'gen/index.html',
data: locals.posts,
layout: ['gen']
}
});
第二步
在主題模板里面創(chuàng)建一個名為gen的模板,里面隨便寫點兒什么
說明
以上的含義就是:
- 當(dāng)hexo g時,創(chuàng)建一個path為“gen/index.html”的靜態(tài)文件,
- 如果訪問http://localhost:4000/gen/index.html,url就指向了這個文件
- 這個文件的layout模板是gen
- index.html里面的內(nèi)容其實是content內(nèi)容 直接引用到頭尾中間
這個功能就是利用代碼創(chuàng)建了一個頁面
第二個小例子
建立有分頁的一個新頁面
第一步
創(chuàng)建新的js
/scripts/demo.js
var pagination = require('hexo-pagination');
hexo.extend.generator.register('demo', function(locals){
return pagination('demo/index.html', locals.posts, {
perPage: 3,
layout: ['archive', 'index'],
data: {__index:"demo"}
});
});
第二步
創(chuàng)建幾篇文章 我利用hexo new post 創(chuàng)建了5篇 post01 post02 post03 post04 post05
因為我設(shè)置了perPage為3,所以必然會分頁
第三步
運(yùn)行 hexo g
可以看到 靜態(tài)文件已經(jīng)生成 并且自動創(chuàng)建了分頁

需要注意的是 文件夾的名字叫index.html
第四步
手動敲入 http://localhost:4000/demo/index.html/
得到的是以archive為模板的一個頁面 而且分頁已經(jīng)生成好

需要注意的是 第二頁的url為 http://localhost:4000/demo/index.html/page/2/
完全符合分頁的生成規(guī)則 [base(demo/index.html)+"/"+page/d%]
第三個小例子
自動生成指定路徑的頁面
第一步
scripts/demo.js 再添加新代碼
hexo.extend.generator.register('post', function(locals){
return locals.posts.map(function(post){
return {
path: "book/"+post.path,
data: post,
layout: 'post'
};
});
});
第二步
hexo g
這樣就出現(xiàn)了一個book文件夾 內(nèi)部的文件夾結(jié)構(gòu)與post的原生結(jié)構(gòu)一模一樣

其實也十分好理解 因為我本身用的就是post.path
第三步
輸入 http://localhost:4000/book/2019/01/12/post03/
其所有東西與 http://localhost:4000/2019/01/12/post03/一模一樣
因為我用的是同一個布局和同一個data,僅僅是更換了路徑而已
總結(jié)
我們知道 生成一個頁面只需要返回一個包含path layout data 三項的對象即可
生成多個頁面 可以返回一個包含多個頁面對象的數(shù)組
通過Generator的用法 我們可以得到任意我們想要的一系列頁面
更多generator說明請查看官方文檔