title: 为 Hexo 主题添加评论模块 — Disqus, 多说, 友言 date: 2016-01-02 01:26:48 categories: - 术业专攻 tags: - Hexo permalink: hexo-comments ---

前言

目前自己的主题 [Yelee](https://github.com/MOxFIVE/hexo-theme-yelee) 已支持使用 Disqus, 多说和友言评论,代码逻辑和配置也做了些优化,应该是比较完善了。简单分离整理一下,分享于此,方便大家添加到自己制作或使用的主题中。 ## 文件结构 参考以下文件结构把复制的代码和下载的文件放到合适的位置,必要时自行修改文件引用位置。 ``` yelee/_config.yml -----/layout/_partial/article.ejs ---------------------/comments/disqus.ejs ------------------------------/duoshuo.ejs ------------------------------/youyan.ejs ``` ### 文件下载 > [Hexo 评论模块(Disqus, 多说, 友言).zip](/resources/Hexo评论模块.zip) by MOxFIVE ## 关联模块 在合适位置添加以下代码,以便引入评论模块代码。代码使用我比较熟悉的 EJS 书写,使用 Swig, Jade 等其他模板的,请自行转换。 ``` actionscript <% if (!is_home() && post.comments){ %> <% if (theme.duoshuo.on) { %> <%- partial('comments/duoshuo', { key: post.path, title: post.title, url: config.url+url_for(post.path), }) %> <% } else if (theme.youyan.on) { %> <%- partial('comments/youyan') %> <% } else if (theme.disqus.on) { %> <%- partial('comments/disqus', { shortname: theme.disqus.shortname }) %> <% } else if (config.disqus_shortname) { %> <%- partial('comments/disqus', { shortname: config.disqus_shortname }) %> <% } %> <% } %> ``` ### 代码简析 ``` actionscript <% if (!is_home() && post.comments){ %> <% if (theme.duoshuo.on) { %> <%- partial('comments/duoshuo', { key: post.path, title: post.title, url: config.url+url_for(post.path), }) %> <% } else if (theme.youyan.on) { %> <%- partial('comments/youyan') %> <% } else if (theme.disqus.on) { %> <%- partial('comments/disqus', { shortname: theme.disqus.shortname }) %> <% } else if (config.disqus_shortname) { %> <%- partial('comments/disqus', { shortname: config.disqus_shortname }) %> <% } %> <% } %> ``` ### 新评论系统添加 - 如果你想使用畅言或者其他社会化评论系统,并能灵活切换,请参考上文,新加一个 else if 判断引入服务商提供的代码,同时参考后文的配置添加新的设置项。 ## 配置更新 在主题中添加以下设置项进行评论功能的配置。评论设置为二级选项,因为之前不少人设置了 `duoshuo: true` ,结果都进群聊了。要启用某一个评论系统,只需去掉 on 前的 "#",同时按照说明设置好对应个人账号信息即可。 ``` yaml # >>> Conments 评论系统 <<< # Chose ONE as your comment system and keep others disable. # 选一个作为网站评论系统,其他保持禁用。 disqus: #on: true shortname: # https://help.disqus.com/customer/en/portal/articles/466208-what-s-a-shortname- # It is unnecessary to enable disqus here if # you have set "disqus_shortname" in your site's "_config.yml" duoshuo: #on: true domain: # 是否开启多说评论,http://duoshuo.com/create-site/ # 使用上面网址登陆你的多说,然后创建站点,在 domain 中填入你设定的域名前半部分 # http://<要填的部分>.duoshuo.com (domain只填上<>里的内容,不要填整个网址) youyan: #on: true id: # 是否开启友言评论,http://www.uyan.cc/index.php # id 中填写你的友言用户数字ID,注册后进入后台管理即可查看 # 友言服务在 Web 环境下运行,普通本地环境无法查看,请部署后在线上测试。 # >>> <<< ``` ## 模块代码 模块代码已附在下载文件中,在此同时列出备用。依旧是使用 EJS 编写,引入一些信息,设置了几个变量,使用其他模板引擎请自行转换。所有评论模块都设置了 `id="comments"`,以便有需要时通过锚点定位跳转到评论区。 ### Disqus ``` html
``` ### 多说评论 ``` html
``` ### 友言评论 ``` erb
``` ## 相关链接 1. **多说评论**: 1. **友言评论**: 1. **Disqus**: 1. ***refactor: comments code & configuration 评论模块优化*** by **MOxFIVE** on 2016/01/01: