resources.ExecuteAsTemplate

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 }};
}

並且您的站點配置包含:

[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 }}

上述範例:

  1. 捕獲模板作為資源
  2. 執行該資源作為模板,並將當前頁面作為上下文
  3. 將資源發佈為 css/main.css

結果是:

public/css/main.css
body {
  background-color: #fefefe;
  color: #222;
}