配置 Hugo
配置文件
在你的項目目錄根目錄中創建一個網站配置文件,命名為 hugo.toml、hugo.yaml 或 hugo.json,並按照此優先順序進行處理。
my-project/
└── hugo.toml
一個簡單的範例:
baseURL: https://example.org/
languageCode: en-us
params:
contact:
email: info@example.org
phone: +1 202-555-1212
subtitle: The Best Widgets on Earth
title: ABC Widgets, Inc.
baseURL = 'https://example.org/'
languageCode = 'en-us'
title = 'ABC Widgets, Inc.'
[params]
subtitle = 'The Best Widgets on Earth'
[params.contact]
email = 'info@example.org'
phone = '+1 202-555-1212'
{
"baseURL": "https://example.org/",
"languageCode": "en-us",
"params": {
"contact": {
"email": "info@example.org",
"phone": "+1 202-555-1212"
},
"subtitle": "The Best Widgets on Earth"
},
"title": "ABC Widgets, Inc."
}
若要在構建網站時使用不同的配置文件,請使用 --config 標誌:
hugo --config other.toml
將兩個或更多的配置文件合併,按左到右的優先順序:
hugo --config a.toml,b.yaml,c.json
配置目錄
你可以選擇將配置分割為環境、根配置鍵和語言。例如:
my-project/
└── config/
├── _default/
│ ├── hugo.toml
│ ├── menus.en.toml
│ ├── menus.de.toml
│ └── params.toml
└── production/
└── params.toml
根配置鍵有 build、caches、cascade、deployment、frontmatter、imaging、languages、markup、mediatypes、menus、minify、module、outputformats、outputs、params、permalinks、privacy、related、security、segments、server、services、sitemap 和 taxonomies。
遺漏根鍵
當根據配置鍵拆分配置時,應在給定的文件中省略根鍵。例如,以下兩種方式是等效的:
params:
foo: bar
[params]
foo = 'bar'
{
"params": {
"foo": "bar"
}
}
foo: bar
foo = 'bar'
{
"foo": "bar"
}
遞歸解析
Hugo 遞歸解析 config 目錄,允許你將文件組織到子目錄中。例如:
my-project/
└── config/
└── _default/
├── navigation/
│ ├── menus.de.toml
│ └── menus.en.toml
└── hugo.toml
範例
my-project/
└── config/
├── _default/
│ ├── hugo.toml
│ ├── menus.en.toml
│ ├── menus.de.toml
│ └── params.toml
├── production/
│ ├── hugo.toml
│ └── params.toml
└── staging/
├── hugo.toml
└── params.toml
根據上面的結構,當運行 hugo --environment staging 時,Hugo 會使用來自 config/_default 的所有設置,並將 staging 目錄中的設置合併到這些設置上。
假設你正在使用 Google Analytics 來跟踪你的網站,這要求你在網站配置中指定一個 Google tag ID:
services:
googleAnalytics:
ID: G-XXXXXXXXX
[services]
[services.googleAnalytics]
ID = 'G-XXXXXXXXX'
{
"services": {
"googleAnalytics": {
"ID": "G-XXXXXXXXX"
}
}
}
現在考慮以下情況:
-
你不希望在運行
hugo server時加載分析代碼。 -
你希望在生產和測試環境中使用不同的 Google tag IDs,例如:
G-PPPPPPPPP用於生產G-SSSSSSSSS用於測試
為了滿足這些要求,按以下方式配置你的網站:
-
config/_default/hugo.toml排除
services.googleAnalytics部分,這將防止在運行hugo server時加載分析代碼。默認情況下,Hugo 在運行
hugo server時會將environment設置為development。在沒有config/development目錄的情況下,Hugo 將使用config/_default目錄。 -
config/production/hugo.toml僅包含以下部分:
hugo.services: googleAnalytics: ID: G-PPPPPPPPP[services] [services.googleAnalytics] ID = 'G-PPPPPPPPP'{ "services": { "googleAnalytics": { "ID": "G-PPPPPPPPP" } } }你不需要在此文件中包含其他參數,只需包含對於生產環境特定的參數即可。Hugo 會將這些參數與默認配置合併。
默認情況下,Hugo 在運行
hugo時會將environment設置為production,因此分析代碼將使用G-PPPPPPPPPtag ID。 -
config/staging/hugo.toml僅包含以下部分:
hugo.services: googleAnalytics: ID: G-SSSSSSSSS[services] [services.googleAnalytics] ID = 'G-SSSSSSSSS'{ "services": { "googleAnalytics": { "ID": "G-SSSSSSSSS" } } }你不需要在此文件中包含其他參數,只需包含對於測試環境特定的參數即可。Hugo 會將這些參數與默認配置合併。
要構建測試站點,請運行
hugo --environment staging。此時,分析代碼將使用G-SSSSSSSSStag ID。
從主題中合併配置
_merge 的配置值可以是以下之一:
- none: 不進行合併。
- shallow: 只為新鍵添加值。
- deep: 為新鍵添加值並合併現有鍵。
請注意,你不需要像下面的默認設置那樣冗長;如果沒有設置,較高層級的 _merge 值會被繼承。
build:
_merge: none
caches:
_merge: none
cascade:
_merge: none
deployment:
_merge: none
frontmatter:
_merge: none
httpcache:
_merge: none
imaging:
_merge: none
languages:
_merge: none
en:
_merge: none
menus:
_merge: shallow
params:
_merge: deep
markup:
_merge: none
mediatypes:
_merge: shallow
menus:
_merge: shallow
minify:
_merge: none
module:
_merge: none
outputformats:
_merge: shallow
outputs:
_merge: none
page:
_merge: none
pagination:
_merge: none
params:
_merge: deep
permalinks:
_merge: none
privacy:
_merge: none
related:
_merge: none
security:
_merge: none
segments:
_merge: none
server:
_merge: none
services:
_merge: none
sitemap:
_merge: none
taxonomies:
_merge: none
[build]
_merge = 'none'
[caches]
_merge = 'none'
[cascade]
_merge = 'none'
[deployment]
_merge = 'none'
[frontmatter]
_merge = 'none'
[httpcache]
_merge = 'none'
[imaging]
_merge = 'none'
[languages]
_merge = 'none'
[languages.en]
_merge = 'none'
[languages.en.menus]
_merge = 'shallow'
[languages.en.params]
_merge = 'deep'
[markup]
_merge = 'none'
[mediatypes]
_merge = 'shallow'
[menus]
_merge = 'shallow'
[minify]
_merge = 'none'
[module]
_merge = 'none'
[outputformats]
_merge = 'shallow'
[outputs]
_merge = 'none'
[page]
_merge = 'none'
[pagination]
_merge = 'none'
[params]
_merge = 'deep'
[permalinks]
_merge = 'none'
[privacy]
_merge = 'none'
[related]
_merge = 'none'
[security]
_merge = 'none'
[segments]
_merge = 'none'
[server]
_merge = 'none'
[services]
_merge = 'none'
[sitemap]
_merge = 'none'
[taxonomies]
_merge = 'none'
{
"build": {
"_merge": "none"
},
"caches": {
"_merge": "none"
},
"cascade": {
"_merge": "none"
},
"deployment": {
"_merge": "none"
},
"frontmatter": {
"_merge": "none"
},
"httpcache": {
"_merge": "none"
},
"imaging": {
"_merge": "none"
},
"languages": {
"_merge": "none",
"en": {
"_merge": "none",
"menus": {
"_merge": "shallow"
},
"params": {
"_merge": "deep"
}
}
},
"markup": {
"_merge": "none"
},
"mediatypes": {
"_merge": "shallow"
},
"menus": {
"_merge": "shallow"
},
"minify": {
"_merge": "none"
},
"module": {
"_merge": "none"
},
"outputformats": {
"_merge": "shallow"
},
"outputs": {
"_merge": "none"
},
"page": {
"_merge": "none"
},
"pagination": {
"_merge": "none"
},
"params": {
"_merge": "deep"
},
"permalinks": {
"_merge": "none"
},
"privacy": {
"_merge": "none"
},
"related": {
"_merge": "none"
},
"security": {
"_merge": "none"
},
"segments": {
"_merge": "none"
},
"server": {
"_merge": "none"
},
"services": {
"_merge": "none"
},
"sitemap": {
"_merge": "none"
},
"taxonomies": {
"_merge": "none"
}
}
所有配置設置
archetypeDir
(string) Hugo 查找原型文件(內容模板)的目錄。默認值為 archetypes。另請參閱 模組掛載配置,了解配置此目錄的替代方法。
assetDir
(string) Hugo 查找用於Hugo Pipes 的資源文件的目錄。默認值為 assets。另請參閱 模組掛載配置,了解配置此目錄的替代方法。
baseURL
(string) 你的發布網站的絕對 URL(協議、主機、路徑和結尾的斜杠),例如 https://www.example.org/docs/。
build
參見配置構建。
buildDrafts
(bool) 構建時是否包含草稿。默認值為 false。
buildExpired
(bool) 構建時是否包含已過期的內容。默認值為 false。
buildFuture
(bool) 構建時是否包含未來發布的內容。默認值為 false。
caches
參見配置文件快取。
canonifyURLs
(bool) 在啟用此功能之前,請參見詳細資料。默認值為 false。
capitalizeListTitles
New in v0.123.3(bool) 是否將自動生成的列表標題首字母大寫。適用於章節、分類和術語頁面。默認值為 true。你可以在網站配置中將大寫樣式更改為 ap、chicago、go、firstupper 或 none。參見詳細資料。
cascade
將默認的配置值(頁面元資料)傳遞給內容樹中的頁面。站點配置中的選項與頁面元資料中的選項相同,請參見前置元資料瀑布流。
cleanDestinationDir
(bool) 在構建時,從目標資料夾移除在靜態目錄中找不到的檔案。預設值為 false。
contentDir
(string) Hugo 讀取內容檔案的資料夾。預設為 content。另請參閱 模組掛載配置,了解配置此目錄的替代方法。
copyright
(string) 用於網站的版權聲明,通常顯示在頁尾。
dataDir
(string) Hugo 讀取資料檔案的資料夾。預設為 data。另請參閱 模組掛載配置,了解配置此目錄的替代方法。
defaultContentLanguage
(string) 沒有語言指示的內容將預設為此語言。預設為 en。
defaultContentLanguageInSubdir
(bool) 在子目錄中渲染預設內容語言,例如 content/en/。網站根目錄 / 將重定向到 /en/。預設為 false。
disableAliases
(bool) 禁用別名重定向的生成。即使設定了 disableAliases,別名本身仍會保留在頁面中。這樣做的目的是能夠生成 301 重定向,並可在 .htaccess、Netlify _redirects 文件或類似的地方使用自定義輸出格式。預設為 false。
disableHugoGeneratorInject
(bool) Hugo 預設會在首頁的 HTML 頭部注入生成器 meta 標籤。可以將其關閉,但如果您不關閉的話,我們會非常感激,這是一個觀察 Hugo 流行度上升的好方法。預設為 false。
disableKinds
(string slice) 禁用渲染指定的頁面 [種類],包括 404、home、page、robotstxt、rss、section、sitemap、taxonomy、term。
disableLanguages
請參見 禁用語言。
disableLiveReload
(bool) 禁用瀏覽器視窗的自動即時重新加載。預設為 false。
disablePathToLower
(bool) 不將 URL/路徑轉為小寫。預設為 false。
enableEmoji
(bool) 啟用 Emoji 表情符號支持於頁面內容中;詳見 emoji shortcode 快速參考指南。預設為 false。
enableGitInfo
(bool) 啟用 .GitInfo 物件於每頁(若 Hugo 網站為 Git 版本管理)。此設定將根據最後一次 Git 提交日期更新每頁的 Lastmod 參數。預設為 false。
enableMissingTranslationPlaceholders
(bool) 若缺少翻譯,顯示佔位符,而不是顯示預設值或空字串。預設為 false。
enableRobotsTXT
(bool) 啟用 robots.txt 文件的生成。預設為 false。
environment
(string) 建構環境。當執行 hugo 時,預設為 production,而執行 hugo server 時,預設為 development。請參見 配置目錄。
frontmatter
請參見 Front matter 配置。
hasCJKLanguage
(bool) 若為 true,會自動檢測內容中的中文/日文/韓文語言。這將使 .Summary 和 .WordCount 在 CJK 語言中正確運作。預設為 false。
ignoreCache
(bool) 忽略快取資料夾。預設為 false。
ignoreLogs
(string slice) 一組訊息識別符,用來對應於您希望抑制的警告和錯誤。詳見 erroridf 和 warnidf。
ignoreVendorPaths
(string) 忽略在 _vendor 目錄內符合給定 Glob 模式的已註冊模塊。
imaging
請參見 影像處理配置。
languageCode
(string) 由 RFC 5646 定義的語言標籤。此值會用來填充:
- 嵌入式 RSS 模板 中的
<language>元素 - 嵌入式 別名模板 中的
<html>元素的lang屬性 - 嵌入式 Open Graph 模板 中的
og:localemeta元素
當此值位於配置根目錄時,若存在一個或多個語言鍵,則此值將被忽略。請為每個語言鍵獨立指定此值。
languages
請參見 配置語言。
layoutDir
(string) 包含模板的資料夾。預設為 layouts。
markup
請參見 配置標記語法。
mediaTypes
請參見 配置媒體類型。
menus
請參見 菜單。
minify
請參見 配置壓縮。
module
模塊配置請參見 模塊配置。
newContentEditor
(string) 創建新內容時所使用的編輯器。
noBuildLock
(bool) 不生成 .hugo_build.lock 檔案。預設為 false。
noChmod
(bool) 不同步檔案的權限模式。預設為 false。
noTimes
(bool) 不同步檔案的修改時間。預設為 false。
outputFormats
請參見 [自定義輸出格式]。
page
請參見 配置頁面。
pagination
請參見 配置分頁。
panicOnWarning
(bool) 是否在遇到第一個警告時就報錯。預設為 false。
permalinks
請參見 內容管理。
pluralizeListTitles
(bool) 是否對自動產生的列表標題進行複數化。適用於區段頁面。預設為 true。
printI18nWarnings
(bool) 是否記錄每個缺失翻譯的警告。預設為 false。
printPathWarnings
(bool) 是否記錄當 Hugo 將多個檔案發布到相同路徑時的警告。預設為 false。
printUnusedTemplates
(bool) 是否記錄每個未使用模板的警告。預設為 false。
publishDir
(string) Hugo 寫入最終靜態網站(HTML 檔案等)的目標資料夾。預設為 public。
refLinksErrorLevel
(string) 當使用 ref 或 relref 解析頁面連結時,如果無法解析某個連結,將以此記錄等級登錄。有效值為 ERROR(預設)或 WARNING。任何 ERROR 都將導致構建失敗(exit -1)。預設為 ERROR。
refLinksNotFoundURL
(string) 當頁面引用無法找到時,作為佔位符使用的 URL。原樣使用。
related
請參見 相關內容。
relativeURLs
(bool) 在啟用此功能前,請參見 詳細資料。預設為 false。
removePathAccents
(bool) 移除內容路徑中的 非間距符號 以及 複合字符。預設為 false。
content/post/hügó.md → https://example.org/post/hugo/
renderSegments
New in v0.124.0(string slice) 一組待渲染的片段。如果未設置,將渲染所有片段。這通常會在 CLI 標誌中設置,例如 hugo --renderSegments segment1,segment2。片段名稱必須與 片段 配置中的名稱匹配。
sectionPagesMenu
請參見 菜單。
security
請參見 安全政策。
segments
請參見 片段。
sitemap
預設的 網站地圖配置。
summaryLength
(int) 適用於 自動摘要,調用 Page 物件的 Summary 方法時要渲染的最少字數。在這種情況下,Summary 方法將返回內容,並將其截斷至與 summaryLength 最接近的段落。
taxonomies
請參見 配置分類法。
templateMetrics
(bool) 是否將模板執行指標打印到控制台。預設為 false。請參見 模板指標。
templateMetricsHints
(bool) 是否在控制台列印模板執行效能提升建議。適用於當 templateMetrics 為 true 時。預設為 false。詳情請參見模板效能指標。
theme
參見模組設定了解如何匯入主題。
themesDir
(string) Hugo 讀取主題檔案的目錄。預設為 themes。
timeout
(string) 生成頁面內容的超時時間,可以指定為持續時間或以秒為單位。*注意:*此設置用於避免遞迴內容生成。如果你的頁面生成速度較慢(例如,因為需要處理大型影像或依賴遠端內容),可能需要提高此限制。預設為 30s。
timeZone
(string) 用於解析沒有時區偏移的日期(包括前置資料區塊的日期欄位及傳遞給time.AsTime和time.Format模板函數的值)的時區。有效值清單可能依系統而異,但應包含 UTC、Local 和IANA 時區資料庫中的任何地點。例如,America/Los_Angeles 和 Europe/Oslo 是有效的時區。
title
(string) 網站標題。
titleCaseStyle
(string) 預設為 ap。參見配置標題大小寫。
uglyURLs
(bool 或 map) 是否生成醜陋的 URL。預設為 false。詳情請參見細節。
watch
(bool) 監控檔案系統變更並根據需要重新生成。預設為 false。
配置頁面
New in v0.133.0Page 物件上的這些方法可在頁面集合中導航至下一頁或上一頁,這是相對於當前頁面:
Hugo 根據以下排序層級來確定“下一頁”和“上一頁”:
| 欄位 | 優先順序 | 排序方向 |
|---|---|---|
weight |
1 | 降序 |
date |
2 | 降序 |
linkTitle |
3 | 降序 |
path |
4 | 降序 |
上表中的排序方向對應到以下預設網站配置值:
page:
nextPrevInSectionSortOrder: desc
nextPrevSortOrder: desc
[page]
nextPrevInSectionSortOrder = 'desc'
nextPrevSortOrder = 'desc'
{
"page": {
"nextPrevInSectionSortOrder": "desc",
"nextPrevSortOrder": "desc"
}
}
要將所有欄位按升序排序:
page:
nextPrevInSectionSortOrder: asc
nextPrevSortOrder: asc
[page]
nextPrevInSectionSortOrder = 'asc'
nextPrevSortOrder = 'asc'
{
"page": {
"nextPrevInSectionSortOrder": "asc",
"nextPrevSortOrder": "asc"
}
}
配置構建
詳見配置構建。
配置伺服器
僅在運行 hugo server 時適用,允許在開發過程中設定 HTTP 標頭,這樣你可以測試內容安全政策等。配置格式類似於Netlify,但提供了更強大的Glob 匹配:
server:
headers:
- for: /**
values:
Content-Security-Policy: script-src localhost:1313
Referrer-Policy: strict-origin-when-cross-origin
X-Content-Type-Options: nosniff
X-Frame-Options: DENY
X-XSS-Protection: 1; mode=block
[server]
[[server.headers]]
for = '/**'
[server.headers.values]
Content-Security-Policy = 'script-src localhost:1313'
Referrer-Policy = 'strict-origin-when-cross-origin'
X-Content-Type-Options = 'nosniff'
X-Frame-Options = 'DENY'
X-XSS-Protection = '1; mode=block'
{
"server": {
"headers": [
{
"for": "/**",
"values": {
"Content-Security-Policy": "script-src localhost:1313",
"Referrer-Policy": "strict-origin-when-cross-origin",
"X-Content-Type-Options": "nosniff",
"X-Frame-Options": "DENY",
"X-XSS-Protection": "1; mode=block"
}
}
]
}
}
因為這只是“開發用途”,將其放置在 development 環境下可能更有意義:
headers:
- for: /**
values:
Content-Security-Policy: script-src localhost:1313
Referrer-Policy: strict-origin-when-cross-origin
X-Content-Type-Options: nosniff
X-Frame-Options: DENY
X-XSS-Protection: 1; mode=block
[[headers]]
for = '/**'
[headers.values]
Content-Security-Policy = 'script-src localhost:1313'
Referrer-Policy = 'strict-origin-when-cross-origin'
X-Content-Type-Options = 'nosniff'
X-Frame-Options = 'DENY'
X-XSS-Protection = '1; mode=block'
{
"headers": [
{
"for": "/**",
"values": {
"Content-Security-Policy": "script-src localhost:1313",
"Referrer-Policy": "strict-origin-when-cross-origin",
"X-Content-Type-Options": "nosniff",
"X-Frame-Options": "DENY",
"X-XSS-Protection": "1; mode=block"
}
}
]
}
你還可以為伺服器指定簡單的重定向規則。語法與 Netlify 類似。
請注意,status 狀態碼為 200 時,會觸發URL 重寫,這在單頁應用(SPA)情況下是所需的,範例如下:
redirects:
- force: false
from: /myspa/**
status: 200
to: /myspa/
[[redirects]]
force = false
from = '/myspa/**'
status = 200
to = '/myspa/'
{
"redirects": [
{
"force": false,
"from": "/myspa/**",
"status": 200,
"to": "/myspa/"
}
]
}
將 force=true 設定為強制進行重定向,即使該路徑中已經存在內容。請注意,在 Hugo 0.76 版本之前,force 是預設行為,但現在是與 Netlify 保持一致。
404 伺服器錯誤頁面
預設情況下,當運行 hugo server 時,Hugo 會透過 404.html 模板渲染所有 404 錯誤。請注意,如果你已經為伺服器配置添加了一個或多個重定向,你需要明確添加 404 重定向,範例如下:
redirects:
- from: /**
status: 404
to: /404.html
[[redirects]]
from = '/**'
status = 404
to = '/404.html'
{
"redirects": [
{
"from": "/**",
"status": 404,
"to": "/404.html"
}
]
}
對於多語言網站,請將默認內容語言的重定向放在最後:
defaultContentLanguage: en
defaultContentLanguageInSubdir: false
redirects:
- from: /fr/**
status: 404
to: /fr/404.html
- from: /**
status: 404
to: /404.html
defaultContentLanguage = 'en'
defaultContentLanguageInSubdir = false
[[redirects]]
from = '/fr/**'
status = 404
to = '/fr/404.html'
[[redirects]]
from = '/**'
status = 404
to = '/404.html'
{
"defaultContentLanguage": "en",
"defaultContentLanguageInSubdir": false,
"redirects": [
{
"from": "/fr/**",
"status": 404,
"to": "/fr/404.html"
},
{
"from": "/**",
"status": 404,
"to": "/404.html"
}
]
}
如果你的默認內容語言是來自子目錄,則如此配置:
defaultContentLanguage: en
defaultContentLanguageInSubdir: true
redirects:
- from: /fr/**
status: 404
to: /fr/404.html
- from: /**
status: 404
to: /en/404.html
defaultContentLanguage = 'en'
defaultContentLanguageInSubdir = true
[[redirects]]
from = '/fr/**'
status = 404
to = '/fr/404.html'
[[redirects]]
from = '/**'
status = 404
to = '/en/404.html'
{
"defaultContentLanguage": "en",
"defaultContentLanguageInSubdir": true,
"redirects": [
{
"from": "/fr/**",
"status": 404,
"to": "/fr/404.html"
},
{
"from": "/**",
"status": 404,
"to": "/en/404.html"
}
]
}
配置標題大小寫
預設情況下,Hugo 在創建自動章節標題時遵循美國傳媒協會風格手冊中發布的大小寫規則,並且當使用strings.Title函數進行字串轉換時也會遵循這一規則。
若要更改此行為,請在網站配置中將 titleCaseStyle 設定為以下任一值:
- ap
- 使用美國傳媒協會風格手冊中發布的大小寫規則。
- chicago
- 使用芝加哥手冊風格中發布的大小寫規則。
- go
- 將每個單詞的首字母大寫。
- firstupper
- 將第一個單詞的首字母大寫。
- none
- 禁用自動章節標題的轉換,也禁用
strings.Title函數執行的轉換。這對於希望手動設置章節標題大小寫,並跳過主題中strings.Title函數的意見化使用時十分有用。
配置環境變數
- DART_SASS_BINARY
- (
string) Dart Sass 可執行檔的絕對路徑。預設情況下,Hugo 在PATH環境變數中的每個路徑中尋找該可執行檔。 - HUGO_ENVIRONMENT
- (
string) 覆寫預設的 環境,通常為development、staging或production之一。
- HUGO_FILE_LOG_FORMAT
- (
string) 用於顯示錯誤時的檔案路徑、行號和列號的格式字串,或當從短代碼或 Markdown 渲染鉤子中調用Position方法時顯示。有效的標記為:file、:line和:col。預設值為:file::line::col。
- HUGO_MEMORYLIMIT
- (
int) 在渲染網站時,Hugo 可以使用的最大系統記憶體數量,單位為吉比特。預設為總系統記憶體的 25%。 - HUGO_NUMWORKERMULTIPLIER
- (
int) 用於並行處理的工作執行緒數量。預設為邏輯 CPU 的數量。
使用環境變數進行配置
配置的鍵值可以通過操作系統環境變數來定義。
例如,以下命令將有效地在類 Unix 系統上設置網站的標題:
$ env HUGO_TITLE="某個標題" hugo
這在您使用像是 Netlify 這樣的服務來部署網站時非常有用。請參閱 Hugo 文檔中的 Netlify 配置檔案 了解範例。
如果您使用的是蛇形命名(snake_case)的變數名,上述方法將無法使用。Hugo 會通過 HUGO 後的第一個字符來決定使用哪種分隔符。因此,您可以使用如 HUGOxPARAMSxAPI_KEY=abcdefgh 這樣的環境變數,並且可以使用任何合法的 分隔符。
渲染時忽略內容和數據檔案
若要在渲染網站時從 content、data 和 i18n 目錄中排除特定檔案,請將 ignoreFiles 設置為一個或多個正則表達式,以匹配絕對檔案路徑。
例如,要忽略以 .foo 或 .boo 結尾的檔案:
ignoreFiles:
- \.foo$
- \.boo$
ignoreFiles = ['\.foo$', '\.boo$']
{
"ignoreFiles": [
"\\.foo$",
"\\.boo$"
]
}
要使用絕對檔案路徑忽略檔案:
ignoreFiles:
- ^/home/user/project/content/test\.md$
ignoreFiles = ['^/home/user/project/content/test\.md$']
{
"ignoreFiles": [
"^/home/user/project/content/test\\.md$"
]
}
配置前置內容
配置日期
日期在 Hugo 中非常重要,您可以配置 Hugo 如何將日期分配給您的內容頁面。您可以通過在 hugo.toml 中添加 frontmatter 部分來進行設置。
預設配置為:
frontmatter:
date:
- date
- publishdate
- pubdate
- published
- lastmod
- modified
expiryDate:
- expirydate
- unpublishdate
lastmod:
- :git
- lastmod
- modified
- date
- publishdate
- pubdate
- published
publishDate:
- publishdate
- pubdate
- published
- date
[frontmatter]
date = ['date', 'publishdate', 'pubdate', 'published', 'lastmod', 'modified']
expiryDate = ['expirydate', 'unpublishdate']
lastmod = [':git', 'lastmod', 'modified', 'date', 'publishdate', 'pubdate', 'published']
publishDate = ['publishdate', 'pubdate', 'published', 'date']
{
"frontmatter": {
"date": [
"date",
"publishdate",
"pubdate",
"published",
"lastmod",
"modified"
],
"expiryDate": [
"expirydate",
"unpublishdate"
],
"lastmod": [
":git",
"lastmod",
"modified",
"date",
"publishdate",
"pubdate",
"published"
],
"publishDate": [
"publishdate",
"pubdate",
"published",
"date"
]
}
}
例如,若您的內容中有非標準的日期參數,您可以覆寫 date 的設置:
frontmatter:
date:
- myDate
- :default
[frontmatter]
date = ['myDate', ':default']
{
"frontmatter": {
"date": [
"myDate",
":default"
]
}
}
:default 是對預設設置的快捷方式。上面的設定將會把 .Date 設置為 myDate 中的日期值(如果存在)。如果不存在,Hugo 會查找 date、publishDate、lastmod 並選擇第一個有效的日期。
右側列表中,以 : 開頭的值是具有特殊意義的日期處理程式(請參見下文)。其他則是您前置內容配置中日期參數的名稱(不區分大小寫)。還要注意,Hugo 對上述有一些內建的別名:lastmod => modified、publishDate => pubdate、published 及 expiryDate => unpublishdate。舉例來說,使用 pubDate 作為前置內容中的日期時,預設情況下,會被分配給 .PublishDate。
特殊的日期處理器如下:
:fileModTime- 取得內容檔案的最後修改時間戳作為日期。
例如:
frontmatter:
lastmod:
- lastmod
- :fileModTime
- :default
[frontmatter]
lastmod = ['lastmod', ':fileModTime', ':default']
{
"frontmatter": {
"lastmod": [
"lastmod",
":fileModTime",
":default"
]
}
}
上述會首先試圖從 lastmod 前置內容參數中提取 .Lastmod 的值,然後使用內容檔案的修改時間戳。最後的 :default 應該不需要,但 Hugo 最終會尋找 :git、date 或 publishDate 中的有效日期。
:filename- 從內容檔案的檔案名稱中獲取日期。例如,
2018-02-22-mypage.md會提取日期2018-02-22。此外,如果未設置slug,則會將mypage作為.Slug的值。
例如:
frontmatter:
date:
- :filename
- :default
[frontmatter]
date = [':filename', ':default']
{
"frontmatter": {
"date": [
":filename",
":default"
]
}
}
上述將首先嘗試從檔案名稱中提取 .Date,如果提取失敗,則會查找前置內容參數 date、publishDate,最後為 lastmod。
:git- 這是 Git 提交的日期,僅當
--enableGitInfo或enableGitInfo = true在網站配置中設置時才會設置。
配置最小化
請參閱 tdewolff/minify 頁面了解詳細信息。
預設配置:
minify:
disableCSS: false
disableHTML: false
disableJS: false
disableJSON: false
disableSVG: false
disableXML: false
minifyOutput: false
tdewolff:
css:
inline: false
keepCSS2: true
precision: 0
html:
keepComments: false
keepConditionalComments: false
keepDefaultAttrVals: true
keepDocumentTags: true
keepEndTags: true
keepQuotes: false
keepSpecialComments: true
keepWhitespace: false
templateDelims:
- ""
- ""
js:
keepVarNames: false
precision: 0
version: 2022
json:
keepNumbers: false
precision: 0
svg:
inline: false
keepComments: false
precision: 0
xml:
keepWhitespace: false
[minify]
disableCSS = false
disableHTML = false
disableJS = false
disableJSON = false
disableSVG = false
disableXML = false
minifyOutput = false
[minify.tdewolff]
[minify.tdewolff.css]
inline = false
keepCSS2 = true
precision = 0
[minify.tdewolff.html]
keepComments = false
keepConditionalComments = false
keepDefaultAttrVals = true
keepDocumentTags = true
keepEndTags = true
keepQuotes = false
keepSpecialComments = true
keepWhitespace = false
templateDelims = ['', '']
[minify.tdewolff.js]
keepVarNames = false
precision = 0
version = 2022
[minify.tdewolff.json]
keepNumbers = false
precision = 0
[minify.tdewolff.svg]
inline = false
keepComments = false
precision = 0
[minify.tdewolff.xml]
keepWhitespace = false
{
"minify": {
"disableCSS": false,
"disableHTML": false,
"disableJS": false,
"disableJSON": false,
"disableSVG": false,
"disableXML": false,
"minifyOutput": false,
"tdewolff": {
"css": {
"inline": false,
"keepCSS2": true,
"precision": 0
},
"html": {
"keepComments": false,
"keepConditionalComments": false,
"keepDefaultAttrVals": true,
"keepDocumentTags": true,
"keepEndTags": true,
"keepQuotes": false,
"keepSpecialComments": true,
"keepWhitespace": false,
"templateDelims": [
"",
""
]
},
"js": {
"keepVarNames": false,
"precision": 0,
"version": 2022
},
"json": {
"keepNumbers": false,
"precision": 0
},
"svg": {
"inline": false,
"keepComments": false,
"precision": 0
},
"xml": {
"keepWhitespace": false
}
}
}
}
配置檔案快取
自 Hugo 0.52 以來,您可以配置的不僅僅是 cacheDir。這是預設配置:
caches:
assets:
dir: :resourceDir/_gen
maxAge: -1
getcsv:
dir: :cacheDir/:project
maxAge: -1
getjson:
dir: :cacheDir/:project
maxAge: -1
getresource:
dir: :cacheDir/:project
maxAge: -1
images:
dir: :resourceDir/_gen
maxAge: -1
misc:
dir: :cacheDir/:project
maxAge: -1
modules:
dir: :cacheDir/modules
maxAge: -1
[caches]
[caches.assets]
dir = ':resourceDir/_gen'
maxAge = -1
[caches.getcsv]
dir = ':cacheDir/:project'
maxAge = -1
[caches.getjson]
dir = ':cacheDir/:project'
maxAge = -1
[caches.getresource]
dir = ':cacheDir/:project'
maxAge = -1
[caches.images]
dir = ':resourceDir/_gen'
maxAge = -1
[caches.misc]
dir = ':cacheDir/:project'
maxAge = -1
[caches.modules]
dir = ':cacheDir/modules'
maxAge = -1
{
"caches": {
"assets": {
"dir": ":resourceDir/_gen",
"maxAge": -1
},
"getcsv": {
"dir": ":cacheDir/:project",
"maxAge": -1
},
"getjson": {
"dir": ":cacheDir/:project",
"maxAge": -1
},
"getresource": {
"dir": ":cacheDir/:project",
"maxAge": -1
},
"images": {
"dir": ":resourceDir/_gen",
"maxAge": -1
},
"misc": {
"dir": ":cacheDir/:project",
"maxAge": -1
},
"modules": {
"dir": ":cacheDir/modules",
"maxAge": -1
}
}
}
您可以在自己的 hugo.toml 配置中覆寫這些快取設置。
解釋關鍵字
- cacheDir
- (
string) 請參見 配置 cacheDir。 - project
- (
string) 當前 Hugo 項目的基目錄名稱。這意味著,每個項目將有各自分開的檔案快取,這樣當您執行hugo --gc時,其他 Hugo 項目的檔案不會被觸及。 - resourceDir
- (
string) 這是resourceDir配置選項的值。 - maxAge
- (
string) 此快取條目被駁回之前的時間,-1 意味著永遠不會駁回,0 會實際關閉該快取。使用 Go 的time.Duration,所以有效值有"10s"(10 秒)、"10m"(10 分鐘)和"10h"(10 小時)。 - dir
- (
string) 儲存此快取檔案的絕對路徑。允許使用:cacheDir和:resourceDir(見上方)作為起始佔位符。
配置 cacheDir
這是 Hugo 預設儲存檔案快取的目錄。請參見 配置檔案快取。
您可以使用 cacheDir 配置選項或操作系統環境變數 HUGO_CACHEDIR 來設置。
如果未設置,Hugo 會根據優先順序使用以下位置:
- 如果在 Netlify 上運行:
/opt/build/cache/hugo_cache/。這意味著,如果您在 Netlify 上運行構建,所有配置有:cacheDir的快取將會保存並在下一次構建時恢復。對於其他 CI 供應商,請閱讀他們的文檔。例如,可以參考 CircleCI 配置。 - 在操作系統使用者快取目錄下的
hugo_cache目錄內,這由 Go 的 os.UserCacheDir 定義。對於類 Unix 系統,這通常是$XDG_CACHE_HOME(根據 basedir-spec-latest 設定),若此目錄為空則為$HOME/.cache;對於 MacOS,則是$HOME/Library/Caches;對於 Windows,則是%LocalAppData%;對於 Plan 9 系統,則是$home/lib/cache。 New in v0.116.0 - 在操作系統的臨時目錄下的
hugo_cache_$USER目錄內。
若要查看當前的 cacheDir 設置,您可以運行 hugo config,例如:hugo config | grep cachedir。
配置 HTTP 快取
New in v0.127.0請注意,此配置目前僅在使用 resources.GetRemote 函數時相關。
Hugo 中的快取是分層的:
- 動態快取 (Dynacache)
- 一個記憶體中的 LRU 快取,當變更、快取破壞器 匹配或者記憶體不足時會被清除。
- HTTP 快取
- 為遠程資源啟用 HTTP 快取行為 (RFC 9111)。這對於正確設置了 HTTP 快取標頭的資源最為有效。HTTP 快取使用 文件快取 來儲存和服務快取的資源。
- 文件快取
- 參見 文件快取。
預設情況下,HTTP 快取將禁用所有功能:
HTTPCache:
cache:
for:
excludes:
- '**'
includes: null
polls:
- disable: true
for:
excludes: null
includes:
- '**'
high: 0s
low: 0s
[HTTPCache]
[HTTPCache.cache]
[HTTPCache.cache.for]
excludes = ['**']
[[HTTPCache.polls]]
disable = true
high = '0s'
low = '0s'
[HTTPCache.polls.for]
includes = ['**']
{
"HTTPCache": {
"cache": {
"for": {
"excludes": [
"**"
],
"includes": null
}
},
"polls": [
{
"disable": true,
"for": {
"excludes": null,
"includes": [
"**"
]
},
"high": "0s",
"low": "0s"
}
]
}
}
- caching
- 啟用為配置的資源集設定的 RFC 9111 快取行為。即使其設定的 TTL 沒有到期,過時的資源也會從 文件快取 中刷新。
- polling
- 為資源集啟用輪詢。請注意,即使禁用 HTTP 快取,您也可以啟用資源的輪詢。此設置僅在觀察模式下使用(例如,
hugo server)。當檢測到有資源變更時,該變更會觸發頁面重建,並使用該資源進行重建。
配置段 (Segments)
New in v0.124.0- 每個段落由零個或多個
exclude過濾器和零個或多個include過濾器組成。 - 每個過濾器由一個或多個欄位 Glob 匹配器組成。
- 每個段落中的過濾器 (
exclude或include) 是 OR 關係,每個過濾器中的匹配器是 AND 關係。
可以在過濾器中使用的欄位包括:
建議將粗粒度的過濾器(例如語言和輸出格式)放在 exclude 區段中,例如:
segments:
segment1:
excludes:
- lang: n*
- lang: en
output: rss
includes:
- kind: '{home,term,taxonomy}'
- path: '{/docs,/docs/**}'
[segments]
[segments.segment1]
[[segments.segment1.excludes]]
lang = 'n*'
[[segments.segment1.excludes]]
lang = 'en'
output = 'rss'
[[segments.segment1.includes]]
kind = '{home,term,taxonomy}'
[[segments.segment1.includes]]
path = '{/docs,/docs/**}'
{
"segments": {
"segment1": {
"excludes": [
{
"lang": "n*"
},
{
"lang": "en",
"output": "rss"
}
],
"includes": [
{
"kind": "{home,term,taxonomy}"
},
{
"path": "{/docs,/docs/**}"
}
]
}
}
}
如上所示,您可以通過配置 renderSegments 或設置 --renderSegments 標誌來僅渲染 segment1 中的頁面:
hugo --renderSegments segment1
可以配置多個段落,並且 --renderSegments 標誌可以接受用逗號分隔的段落列表。
此功能的一些使用案例:
- 拆分大型網站的構建。
- 使開發期間的構建更快速,只渲染網站的一部分。
- 部分重建,例如每小時渲染首頁和「新聞區」,每週渲染整個網站一次。
- 僅渲染例如 JSON 輸出格式以推送到例如搜尋索引。