templates.Defer
New in v0.128.0
在某些特殊情況下,您可能需要延遲執行模板,直到所有網站和輸出格式均已渲染完成。例如,TailwindCSS 使用 hugo_stats.json 的輸出來決定在最終輸出中使用的類別和其他 HTML 標識符:
{{ with (templates.Defer (dict "key" "global")) }}
{{ $t := debug.Timer "tailwindcss" }}
{{ with resources.Get "css/styles.css" }}
{{ $opts := dict
"inlineImports" true
"optimize" hugo.IsProduction
}}
{{ with . | css.TailwindCSS $opts }}
{{ if hugo.IsDevelopment }}
<link rel="stylesheet" href="{{ .RelPermalink }}" />
{{ else }}
{{ with . | minify | fingerprint }}
<link
rel="stylesheet"
href="{{ .RelPermalink }}"
integrity="{{ .Data.Integrity }}"
crossorigin="anonymous" />
{{ end }}
{{ end }}
{{ end }}
{{ end }}
{{ $t.Stop }}
{{ end }}
為了使上述在伺服器運行時(或 hugo -w
),您希望有以下類型的配置:
hugo.
build:
buildStats:
enable: true
cachebusters:
- source: assets/notwatching/hugo_stats\.json
target: styles\.css
- source: (postcss|tailwind)\.config\.js
target: css
module:
mounts:
- disableWatch: true
source: hugo_stats.json
target: assets/notwatching/hugo_stats.json
[build]
[build.buildStats]
enable = true
[[build.cachebusters]]
source = 'assets/notwatching/hugo_stats\.json'
target = 'styles\.css'
[[build.cachebusters]]
source = '(postcss|tailwind)\.config\.js'
target = 'css'
[module]
[[module.mounts]]
disableWatch = true
source = 'hugo_stats.json'
target = 'assets/notwatching/hugo_stats.json'
{
"build": {
"buildStats": {
"enable": true
},
"cachebusters": [
{
"source": "assets/notwatching/hugo_stats\\.json",
"target": "styles\\.css"
},
{
"source": "(postcss|tailwind)\\.config\\.js",
"target": "css"
}
]
},
"module": {
"mounts": [
{
"disableWatch": true,
"source": "hugo_stats.json",
"target": "assets/notwatching/hugo_stats.json"
}
]
}
}
選項
templates.Defer
函數接受一個參數,一個包含以下可選鍵的地圖:
- key (
字串
) - 用於延遲模板的鍵。這將與模板內容的哈希結合,用於作為快取鍵。如果未設置此值,Hugo 將在每次呈現時執行延遲的模板。這不是為共享資源(如 CSS 和 JavaScript)所期望的。
- data (
地圖
) - 可選的地圖,傳遞為延遲模板的數據。這將在延遲模板中作為
.
或$
可用。
Language Outside: {{ site.Language.Lang }}
Page Outside: {{ .RelPermalink }}
I18n Outside: {{ i18n "hello" }}
{{ $data := (dict "page" . )}}
{{ with (templates.Defer (dict "data" $data )) }}
Language Inside: {{ site.Language.Lang }}
Page Inside: {{ .page.RelPermalink }}
I18n Inside: {{ i18n "hello" }}
{{ end }}
輸出格式、網站、和 語言 將相同,即使執行已延遲。在上面的一個例子中,這意味著 site.Language.Lang
和 .RelPermalink
將在延遲模板的內部和外部相同。