Hexo 使用多说评论框

阿里云产品限时红包,最高 ¥1888 元,立即领取

我们看到很多的博客的文章下面有评论。在 Hexo 上使用这个评论系统,主要有两种,一种是 disqus,另一种是多说。具体使用哪种评论系统,一般是在具体的主题中配置的,也就是在主题下的 _config.yml 文件中。大部分多外的主题都自动集成了 disqus, disqus 也大多在国外使用,它的评论框颜值还是很高的。但是在国内,因为网络访问国外服务比较慢的问题,使用多说会相对好一点。

既然如此,我们以 hueman 主题下在文章末尾配置多说评论框为例作一下说明。

首先,你需要注册一个多说账号并新建一个站点。

多说创建站点

站点创建完成以后,会跳出代码模板的页面,如下:

多说代码模板

左侧选择”获取代码”的这栏,然后选中”通用代码”。这就是我们评论框的代码模板,后面我们需要找到合适的地方,将其插入到 hueman 主题中的文章模板里。

hueman 文章代码

在 hueman 主题中,文章的模板在 hueman -> layout -> _partial -> post -> article.ejs 下面。看到上图中,第一个红框圈住的部分,是主题自带的 disqus 评论框的配置。当然我们没有在项目目录下的 _config.yml 中配置 disqus_shortname,所以它是不生效的,在咱们的文章页面中看不到。

1
2
3
4
5
6
7
<% if (post.comments && config.disqus_shortname){ %>
<section id="comments">
<div id="disqus_thread">
<noscript>Please enable JavaScript to view the <a href="//disqus.com/?ref_noscript">comments powered by Disqus.</a></noscript>
</div>
</section>
<% } %>

找到上面这个文章末尾的位置,仿照上面的逻辑判断代码,把多说评论框模板代码添加进来,如上图中的第二个红框圈住的部分。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<% if (!index && post.comments && theme.duoshuo_shortname){ %>
<section id="comments">
<!-- 多说评论框 start -->
<div class="ds-thread" data-thread-key="<%= post.layout %>-<%= post.slug %>" data-title="<%= post.title %>" data-url="<%= page.permalink %>"></div>
<!-- 多说评论框 end -->
<!-- 多说公共JS代码 start (一个网页只需插入一次) -->
<script type="text/javascript">
var duoshuoQuery = {short_name:'<%= theme.duoshuo_shortname %>'};
(function() {
var ds = document.createElement('script');
ds.type = 'text/javascript';ds.async = true;
ds.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') + '//static.duoshuo.com/embed.js';
ds.charset = 'UTF-8';
(document.getElementsByTagName('head')[0]
|| document.getElementsByTagName('body')[0]).appendChild(ds);
})();
</script>
<!-- 多说公共JS代码 end -->
</section>
<% } %>

这里大家注意一下:

1. 第一行中判断 !index 代表是非主页的文章。我们是要在主页之外的文章正文下添加评论,所以添加了这个判断。

2. theme.duoshuo_shortname,这里需要我们在主题下面的 _config.yml 中添加 duoshuo_shortname 字段配置才能生效。这里和上面讲到的 config.disqus_shortname 的区别就在于 theme._ 开头的是在主题中的 _config.yml 配置, config._ 开头是在项目目录下的 _config.yml 配置。

Ok,到这里,打开 hueman -> _config.yml 在其中添加如下代码:

1
2
# comments 配置多说评论
duoshuo_shortname: 这里就是你在创建站点时填的多说域名

如果多说域名是 http://abc.duoshuo.com , 那这里 duoshuo_shortname 就是 abc。

3. 多说评论框模板中的变量,我们需要进行替换。原来如下:

1
<div class="ds-thread" data-thread-key="请将此处替换成文章在你的站点中的ID" data-title="请替换成文章的标题" data-url="请替换成文章的网址"></div>

替换成:

1
<div class="ds-thread" data-thread-key="<%= post.layout %>-<%= post.slug %>" data-title="<%= post.title %>" data-url="<%= page.permalink %>"></div>

其中, post.layoutpost.slugpost.titlepage.permalink 都是 Hexo 的内置变量。具体可以查看这里

多说文章管理

这样就为 Hexo 站点添加上多说评论框啦,如果还需要在其他的位置添加,过程类似。总结下步骤:

  1. 注册多说账号,创建新站点。
  2. 找到需要添加多说评论框的位置,粘贴多说评论框的模板代码,并作必要的修改。
  3. 如果将多说评论框作为配置项,合适的地方,添加配置。