輔助函數

輔助函數可以讓您輕鬆地將程式碼片段快速添加到模板中。當您處理更複雜的程式碼時,我們建議使用輔助函數而不是模板。

輔助函數無法從 source 資料夾中的檔案存取。

概要

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

範例

hexo.extend.helper.register("js", function (path) {
return '<script src="' + path + '"></script>';
});
<%- js('script.js') %>
// <script src="script.js"></script>

常見問題

自訂輔助函數應放置在哪裡?

請將其放置於 scripts/themes/<yourtheme>/scripts/ 資料夾下。

如何在自訂輔助函數中使用另一個已註冊的輔助函數?

所有輔助函數都在相同的上下文中執行。例如,要在自訂輔助函數中使用 url_for()

hexo.extend.helper.register("lorem", function (path) {
return '<script src="' + this.url_for(path) + '"></script>';
});

如何在另一個擴充功能(例如 Filter、Injector)中使用已註冊的輔助函數?

hexo.extend.helper.get 將回傳輔助函數,但它需要以 hexo 作為其上下文,所以

const url_for = hexo.extend.helper.get("url_for").bind(hexo);