templates.Defer
语法
templates.Defer OPTIONS
返回值
string
在一些罕见的使用场景中,您可能需要在所有站点和输出格式都渲染完成后再延迟执行模板。一个这样的例子可能是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 (
string
) - 用于延迟模板的键。这将与模板内容的哈希值组合使用,作为缓存键。如果未设置此项,Hugo 将在每次渲染时执行延迟的模板。对于 CSS 和 JavaScript 等共享资源,这不是您想要的行为。
- data (
map
) - 可选映射,作为数据传递给延迟的模板。这将在延迟的模板中以
.
或$
的形式提供。
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
在延迟模板的内部和外部将是相同的。