next-theme接入valine评论插件

前因

之前用Hexo构建了博客,使用的next主题,最近升级了Hexo和next,遇到valine评论插件接入的问题,记录下我的解决方案

解决

首先,需要知道的是,next主题在github上有两个仓库,分别是:

  1. theme-next/hexo-theme-next:https://github.com/theme-next/hexo-theme-next
  2. next-theme/hexo-theme-next:https://github.com/theme-next/hexo-theme-next

Hexo官方网站搜索next,导航的仓库是next-theme/hexo-theme-next,所以这次更新版本,也随之将next主题指向到第二个仓库地址

第一个仓库本身就集成了valine评论系统,直接设置配置文件即可
第二个仓库则还未集成,需要多花费一些功夫

对于最新的next主题,提倡不直接修改下载下来的仓库文件,而是将配置文件移动到最外层,使用_config.next.yml. 这样做的好处是,后续的主题更新,只需git pull,不需要担心文件冲突或者丢失的问题

因此,我们要接入valine评论插件,也基于该原则而行。

next-theme/hexo-theme-next仓库调整了模板引擎,现在改为njk.

当前笔者认为读者已了解valine的配置工作

  1. 配置_config.next.yml

    _config.next.yml配置文件中,对字段custom_file_path下的head,postBodyEnd,style分别启用,结果如下:

     # Define custom file paths.
     # Create your custom files in site directory `source/_data` and uncomment needed files below.
     custom_file_path:
         head: source/_data/head.njk
         #header: source/_data/header.njk
         #sidebar: source/_data/sidebar.njk
         #postMeta: source/_data/post-meta.njk
         postBodyEnd: source/_data/post-body-end.njk
         # footer: source/_data/footer.njk
         # bodyEnd: source/_data/body-end.njk
         #variable: source/_data/variables.styl
         #mixin: source/_data/mixins.styl
         style: source/_data/styles.styl
    
  2. 引入valine.js静态资源到html文件的<head>

    _data文件夹下新建head.njk 并在第一行输入如下内容:

     <script src='//unpkg.com/valine/dist/Valine.min.js'></script>
    
  3. Valine插入到文件底部的comments区域:

    _data文件夹下新建post-body-end.njk,在头部输入如下内容:

    {%- if post.comments %}
    <div id="vcomments"></div>
    <script>
        new Valine({
            el: '#vcomments',
            appId: 'eCHLoB81t36p79wcRNScqm89-gzGzoHsz',
            appKey: '4VKFr7gSGwdAPEQNDYOgg7Hk',
            visitor: true,
        })
    </script>
    {%- endif %}
    
  4. 调整valine评论插件样式:

_data文件夹下新建styles.styl,输入如下内容

 // post valine style

 #vcomments {
     order: 1;
     margin-top: 50px;
     .vpower {
         display: none;    
     }
 }

其他问题

上述工作完成后,还需要注意到一点,在访问不同的博客页面时,Valine均需要执行初始化工作,当前的解决方案是不开启next主题提供的配置项pjax_config.next.yml内容大概如此:

# Easily enable fast Ajax navigation on your website.
# For more information: https://github.com/next-theme/pjax
pjax: false

另,如果post的头部声明了关闭评论:

title: 我的第一篇博文
comments: false
date: 2023-01-04 17:37:26
tags: first

则在最终的渲染页面上,valine评论插件并不会出现

相关链接

posted @ 2023-01-12 20:51  西河  阅读(103)  评论(0编辑  收藏  举报