標籤

標籤允許使用者快速且輕鬆地在文章中插入程式碼片段。

概要

hexo.extend.tag.register(
name,
function (args, content) {
// ...
},
options,
);

兩個參數將會傳遞到標籤函式中:argscontentargs 包含傳遞到標籤外掛的參數,而 content 則是來自標籤外掛的封裝內容。

由於 Hexo 3 中引入了非同步渲染,我們使用 Nunjucks 進行渲染。其行為可能與 Swig 中的行為有些不同。

取消註冊標籤

使用 unregister() 來以自訂函式取代現有的標籤外掛

hexo.extend.tag.unregister(name);

範例

const tagFn = (args, content) => {
content = "something";
return content;
};

// https://hexo.dev.org.tw/docs/tag-plugins#YouTube
hexo.extend.tag.unregister("youtube");

hexo.extend.tag.register("youtube", tagFn);

選項

ends

使用結束標籤。此選項預設為 false

async

啟用非同步模式。此選項預設為 false

範例

不使用結束標籤

插入一個 Youtube 影片。

hexo.extend.tag.register("youtube", function (args) {
var id = args[0];
return (
'<div class="video-container"><iframe width="560" height="315" src="http://www.youtube.com/embed/' +
id +
'" frameborder="0" allowfullscreen></iframe></div>'
);
});

使用結束標籤

插入一個引言。

hexo.extend.tag.register(
"pullquote",
function (args, content) {
var className = args.join(" ");
return (
'<blockquote class="pullquote' +
className +
'">' +
content +
"</blockquote>"
);
},
{ ends: true },
);

非同步渲染

插入一個檔案。

var fs = require("hexo-fs");
var pathFn = require("path");

hexo.extend.tag.register(
"include_code",
function (args) {
var filename = args[0];
var path = pathFn.join(hexo.source_dir, filename);

return fs.readFile(path).then(function (content) {
return "<pre><code>" + content + "</code></pre>";
});
},
{ async: true },
);

Front-matter 和使用者設定

以下任何選項都有效

hexo.extend.tag.register('foo', function (args) {
const [firstArg] = args;

// User config
const { config } = hexo;
const editor = config.author + firstArg;

// Theme config
const { config: themeCfg } = hexo.theme;
if (themeCfg.fancybox) // do something...

// Front-matter
const { title } = this; // article's (post/page) title

// Article's content
const { _content } = this; // original content
const { content } = this; // HTML-rendered content

return 'foo';
});
index.js
hexo.extend.tag.register("foo", require("./lib/foo")(hexo));
lib/foo.js
module.exports = hexo => {
return function fooFn(args) {
const [firstArg] = args;

const { config } = hexo;
const editor = config.author + firstArg;

const { config: themeCfg } = hexo.theme;
if (themeCfg.fancybox) // do something...

const { title, _content, content } = this;

return 'foo';
};
};