Back

在 Hugo 中嵌入 Disqus 留言板並調整 Configuration Variables

在 Disqus 創建新服務

首先申請 Disqus 帳戶,並選擇 “I want to install Disqus on my site”


  Create new Disqus service
Create new Disqus service

輸入 Website Name (可取任意名稱,稍後會用到),接著按下 Create Site 即創建完成


  Input website name & create site
Input website name & create site


在 Hugo 和 Disqus 之間建立聯繫

在 config.toml 加入 disqusShortname 這個變數,將剛才的 Website Name 帶入其中

disqusShortname = "web-notes"  

Hugo 有內建 Disqus template,可以用以下方式嵌入 layout

<div class="disqus-container">
  {{ template "_internal/disqus.html" . }}
</div>

嵌入後自動生成以下程式碼


  Internal Disqus template
Internal Disqus template

  • 綠色區塊: Disqus 留言板顯示位置
  • 紅色區塊: Disqus configuration variables 設定位置 (後面會提到)
  • 藍色區塊: disqusShortname

Disqus configuration variables

由於每一則 blog 文章 (以下統稱 post,皆為 markdown 格式) 都會有不同的討論串,設定 configuration variables 的用意就是由網站向 Disqus 發送識別碼,以區隔相同網域中不同路徑下的討論串。Hugo 可以在 post 的 front matter 中設定三種 Disqus configuration variables:

disqus_title (標題)
初次建立討論串時,如果有設 disqus_title,在 Disqus 顯示的討論串就會以 disqus_title 為標題。如果沒有設定,則以 post 的 title 作為標題。

disqus_identifier (識別碼)
給 post 一串在 blog 中不重複的識別碼 (通常是在 post 生成時自動產生),目的是傳送給 disqus 做比對,如果該識別碼不存在讓就創建新討論串,如果存在就回傳留言內容。若沒有設定 disqus_identifier,則 Disqus 會改用 disqus_url 作為識別基準;如果 disqus_url 也沒設定,則以當下網址 (window.location.href) 作為識別基準。

disqus_url (識別網址)
一串固定網址 (通常是在 post 生成時自動產生,直接對應到當下路徑),如果 disqus_identifier 不存在,就會以 disqus_url 作為識別基準。

以下用一則 post 的 front matter 設定來舉例:

---
title: "Lala"
slug: "yoyo"
disqus_url: "https://web-notes.com/post/lala/"
---
  • Disqus configuration variables 相關設定會被放在 disqus_config function 之中:
    
  Disqus config
    Disqus config
  • 沒有 disqus_title,所以在 Disqus dashboard 可以看到討論串建立時是用 post title 做為標題:
    
  Discussion thread title
    Discussion thread title
  • 沒有 disqus_identifier,所以用 disqus_url 作為識別碼。即使之後更換 post 路徑 (例如這裡的 slug 是 yoyo,也就是說目前 post 的路徑是 https://web-notes.com/post/yoyo/),也依然能夠對應到原先的討論串。
  • 如果 disqus_identifier 和 disqus_url 皆未設定,就會以當下網址作為識別碼送往 Disqus。這樣做的問題在於傳給 Disqus 的識別碼可能是不固定的,例如網址攜帶不同的 query 或是 post 的 slug 改變,都會導致識別碼無法對應而產生新的討論串。

除了 disqus_identifier 權重較高、disqus_url 一定要是網址格式以外,兩者的功能基本上是相同的,最少一定要擇一設定。


補充:在 archetypes 中加入 disqus_identifier

可以在 archetypes/default.md 中設定,產生 new post 時順便加入 disqus_identifier (這裡是用 sha256 對 post name 進行雜湊後再擷取前 6 個字元)

---
title: "{{ .Name }}"
date: {{ .Date }}
disqus_identifier: "{{ substr (sha256 .Name) 0 6 }}"
---

參考資料

Licensed under CC BY-NC-SA 4.0
comments powered by Disqus