自從換到現在的 classic Hugo 主題之後,RSS 就沒排版了,在閱讀器中無法直接閱讀,Hugo 在沒有 rss.xml 的情況下,還是會輸出 index.xml,只是就沒有排版。
而 JN 在 10 月底特地來信告知,並且寫了一篇教學文章,只是 Eddie 太懶的拖到現在才處理。
(超級感謝,這是部落格才可能出現的事情,如果今天是社群平臺就被留言嗆爆了)
加入 layouts/_default/rss.xml
原先的主題有 rss,但是在 theme 的 layouts 裡面,被我換主題之後,就直接一併被移除了,這次直接做在專案 的 layouts 裡面,就不用怕主題換了 rss 就不見。
這段程式碼與官方內建的幾乎一樣,但將關鍵的 .Summary 改成了 .Content:
- .Summary (原本的):會自動抓取文章前 70 個字並移除所有 HTML 標籤。因為沒了
<p>標籤,所有的文字就會擠成一團。 - .Content (修改後的):會輸出完整的 HTML 內容(包括段落、換行、圖片)。
- | html:這會確保 HTML 標籤被轉義成 XML 安全格式(例如
<p>變為<p>),這樣 RSS 閱讀器(如 Feedly, NetNewsWire)才能正確地還原排版。
{{- $pctx := . -}}
{{- if .IsHome -}}{{ $pctx = .Site }}{{- end -}}
{{- $pages := $pctx.RegularPages -}}
{{- $limit := .Site.Config.Services.RSS.Limit -}}
{{- if ge $limit 1 -}}
{{- $pages = $pages | first $limit -}}
{{- end -}}
{{- printf "<?xml version=\"1.0\" encoding=\"utf-8\" standalone=\"yes\"?>" | safeHTML }}
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
<channel>
<title>{{ .Site.Title }}</title>
<link>{{ .Permalink }}</link>
<description>Recent content on {{ .Site.Title }}</description>
<generator>Hugo -- gohugo.io</generator>
<language>{{ .Site.LanguageCode }}</language>
{{ with .Site.Author.email }}<managingEditor>{{.}}{{ with $.Site.Author.name }} ({{.}}){{end}}</managingEditor>{{end}}
{{ with .Site.Author.email }}<webMaster>{{.}}{{ with $.Site.Author.name }} ({{.}}){{end}}</webMaster>{{end}}
{{ with .Site.Copyright }}<copyright>{{.}}</copyright>{{end}}
{{ if not .Date.IsZero }}<lastBuildDate>{{ .Date.Format "Mon, 02 Jan 2006 15:04:05 -0700" | safeHTML }}</lastBuildDate>{{ end }}
{{ with .OutputFormats.Get "RSS" }}
{{ printf "<atom:link href=%q rel=\"self\" type=%q />" .Permalink .MediaType | safeHTML }}
{{ end }}
{{ range $pages }}
<item>
<title>{{ .Title }}</title>
<link>{{ .Permalink }}</link>
<pubDate>{{ .Date.Format "Mon, 02 Jan 2006 15:04:05 -0700" | safeHTML }}</pubDate>
<guid>{{ .Permalink }}</guid>
<!-- 關鍵修改處:使用 .Content 並加上 | html 來保留換行與格式 -->
<description>{{ .Content | html }}</description>
</item>
{{ end }}
</channel>
</rss>