インジェクター

インジェクターは、生成されたHTMLファイルの<head>または/および<body>に静的コードスニペットを追加するために使用されます。Hexoは、after_render:htmlフィルターが実行される**前**にインジェクターを実行します。

概要

hexo.extend.injector.register(entry, value, to);

entry <string>

HTML内のどこにコードが挿入されるかを示します。

以下の値をサポートしています。

  • head_begin: <head>の直後にコードスニペットを挿入します(デフォルト)。
  • head_end: </head>の直前にコードスニペットを挿入します。
  • body_begin: <body>の直後にコードスニペットを挿入します。
  • body_end: </body>の直前にコードスニペットを挿入します。

value <string> | <Function>

文字列を返す関数がサポートされています。

挿入されるコードスニペット。

to <string>

どのページにコードスニペットが挿入されるかを示します。

  • default: すべてのページに挿入します(デフォルト)。
  • home: ホームページ(is_home()ヘルパーがtrueを返すページ)にのみ挿入します。
  • post: 投稿ページ(is_post()ヘルパーがtrueを返すページ)にのみ挿入します。
  • page: 固定ページ(is_page()ヘルパーがtrueを返すページ)にのみ挿入します。
  • archive: アーカイブページ(is_archive()ヘルパーがtrueを返すページ)にのみ挿入します。
  • category: カテゴリページ(is_category()ヘルパーがtrueを返すページ)にのみ挿入します。
  • tag: タグページ(is_tag()ヘルパーがtrueを返すページ)にのみ挿入します。
  • カスタムレイアウト名も使用できます。詳しくはWriting - Layoutをご覧ください。

その他の内部関数もあります。詳しくはhexojs/hexo#4049をご覧ください。

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

hexo.extend.injector.register(
"head_end",
() => {
return css(
"https://cdn.jsdelivr.net/npm/aplayer@1.10.1/dist/APlayer.min.css",
);
},
"music",
);

hexo.extend.injector.register(
"body_end",
'<script src="https://cdn.jsdelivr.net/npm/aplayer@1.10.1/dist/APlayer.min.js">',
"music",
);

hexo.extend.injector.register("body_end", () => {
return js("/js/jquery.js");
});

上記のセットアップでは、レイアウトがmusicのページの</head>APlayer.min.css<link>タグ)が挿入され、それらのページの</body>APlayer.min.js<script>タグ)が挿入されます。また、生成されるすべてのページの</body>jquery.js<script>タグ)が挿入されます。

ユーザー設定へのアクセス

以下のいずれかのオプションを使用してください。

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

hexo.extend.injector.register("head_end", () => {
const { cssPath } = hexo.config.fooPlugin;
return css(cssPath);
});
index.js
/* global hexo */

hexo.extend.injector.register("head_end", require("./lib/inject").bind(hexo));
lib/inject.js
module.exports = function () {
const css = this.extend.helper.get("css");
const { cssPath } = this.config.fooPlugin;
return css(cssPath);
};
lib/inject.js
function injectFn() {
const css = this.extend.helper.get("css");
const { cssPath } = this.config.fooPlugin;
return css(cssPath);
}

module.exports = injectFn;
index.js
/* global hexo */

hexo.extend.injector.register("head_end", require("./lib/inject")(hexo));
lib/inject.js
module.exports = (hexo) => () => {
const css = hexo.extend.helper.get("css").bind(hexo);
const { cssPath } = hexo.config.fooPlugin;
return css(cssPath);
};
lib/inject.js
const injectFn = (hexo) => {
const css = hexo.extend.helper.get("css").bind(hexo);
const { cssPath } = hexo.config.fooPlugin;
return css(cssPath);
};

module.exports = (hexo) => injectFn(hexo);