resources.FromString

resources.FromString 函數會從字串創建一個資源,並使用目標路徑作為其緩存鍵來快取結果。

當您調用該資源的 PublishPermalinkRelPermalink 方法時,Hugo 會將該資源發佈到目標路徑。

假設您需要發佈一個名為 “site.json” 的文件,位於公開目錄的根目錄,文件內容包含構建日期、用來構建網站的 Hugo 版本,還有內容最後修改日期。例如:

{
  "build_date": "2024-02-19T12:27:05-08:00",
  "hugo_version": "0.137.1",
  "last_modified": "2024-02-19T12:01:42-08:00"
}

將此內容放在您的 baseof.html 模板中:

{{ if .IsHome }}
  {{ $rfc3339 := "2006-01-02T15:04:05Z07:00" }}
  {{ $m := dict
    "hugo_version" hugo.Version
    "build_date" (now.Format $rfc3339)
    "last_modified" (site.Lastmod.Format $rfc3339)
  }}
  {{ $json := jsonify $m }}
  {{ $r := resources.FromString "site.json" $json }}
  {{ $r.Publish }}
{{ end }}

上面的範例:

  1. 使用 dict 函數創建一個包含相關鍵值對的映射
  2. 使用 jsonify 函數將該映射編碼為 JSON 字串
  3. 使用 resources.FromString 函數從 JSON 字串創建一個資源
  4. 使用資源的 .Publish 方法將文件發佈到公開目錄的根目錄

如果您的字串包含模板操作,將 resources.FromStringresources.ExecuteAsTemplate 結合使用。改寫上述範例:

{{ if .IsHome }}
  {{ $string := `
    {{ $rfc3339 := "2006-01-02T15:04:05Z07:00" }}
    {{ $m := dict
      "hugo_version" hugo.Version
      "build_date" (now.Format $rfc3339)
      "last_modified" (site.Lastmod.Format $rfc3339)
    }}
    {{ $json := jsonify $m }}
    `
  }}
  {{ $r := resources.FromString "" $string }}
  {{ $r = $r | resources.ExecuteAsTemplate "site.json" . }}
  {{ $r.Publish }}
{{ end }}