resources.ExecuteAsTemplate
语法
resources.ExecuteAsTemplate TARGETPATH CONTEXT RESOURCE
返回值
resource.Resource
resources.ExecuteAsTemplate
函数返回一个从 Go 模板创建的资源,该模板已解析并使用给定上下文执行,并使用目标路径作为其缓存键来缓存结果。
当你调用其 Publish
、Permalink
或 RelPermalink
方法时,Hugo 会将资源发布到目标路径。
假设你有一个 CSS 文件,希望使用站点配置中的值来填充它
assets/css/template.css
body {
background-color: {{ site.Params.style.bg_color }};
color: {{ site.Params.style.text_color }};
}
并且你的站点配置包含
hugo。
params:
style:
bg_color: '#fefefe'
text_color: '#222'
[params]
[params.style]
bg_color = '#fefefe'
text_color = '#222'
{
"params": {
"style": {
"bg_color": "#fefefe",
"text_color": "#222"
}
}
}
将此放置在你的 baseof.html 模板中
{{ with resources.Get "css/template.css" }}
{{ with resources.ExecuteAsTemplate "css/main.css" $ . }}
<link rel="stylesheet" href="{{ .RelPermalink }}">
{{ end }}
{{ end }}
上面的示例
- 将模板捕获为资源
- 将资源作为模板执行,将当前页面传递到上下文中
- 将资源发布到 css/main.css
结果是
public/css/main.css
body {
background-color: #fefefe;
color: #222;
}