如何为 Hexo 实现标签式代码块标签

How to implement a tabbed codeblock tag for Hexo

我正在尝试在 hexo 中创建选项卡式代码块(作为标记插件),但我不知道将 js 函数放在哪里。我以为我可以使用 the js helper 加载函数,但我不知道在哪里包含帮助程序。我尝试将其添加到标签插件中,但失败了。这是标签插件代码(另存为testtag.js):

hexo.extend.tag.register('testtag', function(args, content){
  var className =  args.join(' ');

  var result = '';
  result += "<\%- js('\themes\bootstrap-blog\scripts\tab.js') \%>"
  result += '<div class="tabs">';
  result += '<ul>';
  result += '<li class="li_tab1" onclick="tab(&apos;tab1&apos;)"><a>Tab 1</a></li>';
  result += '<li class="li_tab2" onclick="tab(&apos;tab2&apos;)"><a>Tab 2</a></li>';
  result += '</ul>';
  result += '<div class="contentarea">';
  result += '<div id="tab1">';
  result += '<p>' + content + '</p>';
  result += '</div>';
  result += '<div id="tab2" style="display: none;">'
  result += '<p>This is the text for tab 2.</p>'
  result += '</div>'
  result += '</div>'
  result += '</div>'

  return result;

}, {ends: true});

这确实有效。但是,标签的 onclick 事件只是引发了找不到 tab 函数的错误。请注意,上面 result 的第一行是我使用助手的失败尝试。

这是我的tab函数,tab.js:

function tab(tab) {
document.getElementById('tab1').style.display = 'none';
document.getElementById('tab2').style.display = 'none';
document.getElementById('li_tab1').setAttribute("class", "");
document.getElementById('li_tab2').setAttribute("class", "");
document.getElementById(tab).style.display = 'block';
document.getElementById('li_'+tab).setAttribute("class", "active");
}

tab.jstesttag.js 都保存在 *\themes\bootstrap-blog\scripts* 文件夹中。

我看到了 虽然我可能会有所帮助,但我无法弄清楚视图是什么。我在 Hexo 文档中找不到任何关于视图的信息。

你的代码错误太多,所以我更愿意给你一个完整的例子和解释。

这是我们需要的:

  1. 用于构建此多代码块 HTML 结构的自定义标签
  2. 一个 CSS 文件来风格化代码块和代码着色
  3. 用于为代码块(选项卡)设置动画的 JS 脚本

自定义标签:m_codeblock(JS 服务器端)

我们需要允许用户定义:

  • 一个名字或一个 link
  • 这个选项卡中有多个代码块,所以我们定义了一个标签来分隔和列出每个选项卡

语法如下:

{% m_codeblock [name] [link] %}
    <!-- tab [lang] -->
        source_code
    <!-- endtab -->
{% endm_codeblock %}

还有一个例子:

{% m_codeblock stack overflow https://example.fr %}
    <!-- tab html -->
        <html>
            <body>
                <h1>Hey dan</h1>
            </body>
        </html>
    <!-- endtab -->
    <!-- tab css -->
        h1 {
            color:red;
        }
    <!-- endtab -->
{% endm_codeblock %}        

在您的博客文件夹(不是主题文件夹)中安装这些依赖项:

  • 运行 npm install jsdom --save
  • 运行 npm install jquery --save

这里是这个自定义标签的源代码 themes/theme_name/scripts/m_codeblock.js:

'use strict';

var util = require('hexo-util');
var highlight = util.highlight;
var stripIndent = require('strip-indent');
var rCaptionUrl = /(\S[\S\s]*)\s+(https?:\/\/)(\S+)/i;
var rCaption = /(\S[\S\s]*)/;
var rTab = /<!--\s*tab (\w*)\s*-->\n([\w\W\s\S]*?)<!--\s*endtab\s*-->/g;

// create a window with a document to use jQuery library
require("jsdom").env("", function(err, window) {
    if (err) {
        console.error(err);
        return;
    }

    var $ = require("jquery")(window);

    /**
     * Multi code block
     * @param args
     * @param content
     * @returns {string}
     */
    function multiCodeBlock(args, content) {
        var arg = args.join(' ');
        // get blog config
        var config = hexo.config.highlight || {};

        if (!config.enable) {
            return '<pre><code>' + content + '</code></pre>';
        }

        var html;
        var matches = [];
        var match;
        var caption = '';
        var codes = '';

        // extract languages and source codes
        while (match = rTab.exec(content)) {
            matches.push(match[1]);
            matches.push(match[2]);
        }
        // create tabs and tabs content
        for (var i = 0; i < matches.length; i += 2) {
            var lang = matches[i];
            var code = matches[i + 1];
            var $code;
            // trim code
            code = stripIndent(code).trim();
            // add tab
            // active the first tab
            if (i == 0) {
                caption += '<li class="tab active">' + lang + '</li>';
            }
            else {
                caption += '<li class="tab">' + lang + '</li>';
            }
            // highlight code
            code = highlight(code, {
                lang: lang,
                gutter: config.line_number,
                tab: config.tab_replace,
                autoDetect: config.auto_detect
            });
            // used to parse HTML code and ease DOM manipulation
            // display the first code block
            $code = $('<div>').append(code).find('>:first-child');
            if (i == 0) {
                $code.css('display', 'block');
            }
            else {
                $code.css('display', 'none');
            }

            codes += $code.prop('outerHTML');
        }
        // build caption
        caption = '<ul class="tabs">' + caption + '</ul>';
        // add caption title
        if (rCaptionUrl.test(arg)) {
            match = arg.match(rCaptionUrl);
            caption = '<a href="' + match[2] + match[3] + '">' + match[1] + '</a>' + caption;
        }
        else if (rCaption.test(arg)) {
            match = arg.match(rCaption);
            caption = '<span>' + match[1] + '</span>' + caption;
        }
        codes = '<div class="tabs-content">' + codes + '</div>';
        // wrap caption
        caption = '<figcaption>' + caption + '</figcaption>';
        html = '<figure class="highlight multi">' + caption + codes + '</figure>';
        return html;
    }

    /**
     * Multi code block tag
     *
     * Syntax:
     *   {% m_codeblock %}
     *   <!-- tab [lang] -->
     *       content
     *   <!-- endtab -->
     *   {% endm_codeblock %}
     * E.g:
     *   {% m_codeblock %}
     *   <!-- tab js -->
     *       var test = 'test';
     *   <!-- endtab -->
     *   <!-- tab css -->
     *       .btn {
     *           color: red;
     *       }
     *   <!-- endtab -->
     *   {% endm_codeblock %}
     */
    hexo.extend.tag.register('m_codeblock', multiCodeBlock, {ends: true});
});

阅读评论以理解代码。

All you need to do is put your JavaScript files in the scripts folder and Hexo will load them during initialization.

风格化代码块

默认情况下,只显示第一个选项卡,其他选项卡隐藏,我们在此处的自定义标签源代码中做到了这一点:

$code = $('<div>').append(code).find('>:first-child');
if (i == 0) {
  $code.css('display', 'block');
}
else {
  $code.css('display', 'none');
}

所以您只需要更多 css 来改进用户界面和代码着色。将此文件放入 theme/theme_name/assets/css/style.css 并将其 link 放入布局中。

动画代码块(JS 客户端)

我们需要一些 javascript 来为选项卡设置动画。 当我们点击一​​个选项卡时,必须隐藏所有选项卡内容,只显示右侧选项卡。将此脚本放入 theme/theme_name/assets/js/script.js 并将其 link 放入布局中。

$(document).ready(function() {
  $('.highlight.multi').find('.tab').click(function() {
    var $codeblock = $(this).parent().parent().parent();
    var $tab = $(this);
    // remove `active` css class on all tabs
    $tab.siblings().removeClass('active');
    // add `active` css class on the clicked tab
    $tab.addClass('active');
    // hide all tab contents
    $codeblock.find('.highlight').hide();
    // show only the right one
    $codeblock.find('.highlight.' + $tab.text()).show();
  });  
});

你的问题是构建这个自定义标签的机会,我将把它集成到我开发的下一个版本的 hexo 主题 (Tranquilpeak) 中。

结果如下:

JSFiddle

上实时查看

您还可以创建由父标签读取的内部标签。

{% code_with_tabs %}
  {% code js title="something" class_name="info" %}
    1. aosjaojsdoajsdoajsd
  {% endcode %}
  {% code js title="something" class_name="info" %}
    2. aosjaojsdoajsdoajsd
  {% endcode %}
{% endcode_with_tabs %}

并使用解析器读取生成的内部HTML。