Skip to main content

partialCached

又來幫 Hugo 補充文檔了,partialCached 文檔從頭到尾沒講快取鍵的運作邏輯,沒講快取鍵是要怎麼用快取?

partialCached 介紹

規則很簡單:

  1. 本質:partialCached 就是一個 LRU cache(內部設定最多同時存在一千筆,這數字是 Hugo 內部硬編碼的)
  2. 快取運作:如果沒有 VARIANT,快取鍵就是 LAYOUT(partial 名稱);如果有 VARIANT,快取鍵是 LAYOUT 加上 VARIANT。VARIANT 可以有 0 個或多個,且只用於快取鍵,不參與其他計算

然後兩點注意事項

  1. 每個 site(language, version, role)的快取都獨立互不影響,這裡的 site 指的是 Hugo 的 hugo.Sites
  2. 由於 Hugo 頁面平行渲染,partialCached 可能會重複執行,直到第一個快取鍵建立完成

四點清楚說明,就這麼簡單,包含文檔有講的沒講的全部清楚說明。

看看文檔怎麼寫的

這裡就一定要來鞭文檔了,逐字來看文檔怎麼描述的:

Executes the given template and caches the result, optionally passing one or more variant keys. If the partial template contains a return statement, returns the given value, else returns the rendered output.

Syntax: partials.IncludeCached LAYOUT CONTEXT [VARIANT...]
Returns: any
Alias: partialCached

開頭一般說明,合格。

Without a return statement, the partialCached function returns a string of type template.HTML. With a return statement, the partialCached function can return any data type.

整段廢話,一般的 partial 本身也是這樣運作。

The partialCached function can offer significant performance gains for complex templates that don’t need to be re-rendered on every invocation.

整段廢話,重複描述「快取」這兩個字的意思。

Each site (or language) has its own partialCached cache, so each site will execute a partial template once.

Hugo renders pages in parallel, and will render the partial template more than once with concurrent calls to the partialCached function. After Hugo caches the rendered partial template, new pages entering the build pipeline will use the cached result.

本段內容等同於我寫的注意事項,勉強合格,但是前面寫的是當用戶連 partial 運作都不懂,快取也不懂,這裡又預設用戶懂 hugo.Sites,邏輯矛盾(而且還不給 hugo.Sites 的連結)。

Here is the simplest usage:

{{ partialCached "footer.html" . }}

Pass additional arguments to partialCached to create variants of the cached partial template. For example, if you have a complex partial template that should be identical when rendered for pages within the same section, use a variant based on section so that the partial template is only rendered once per section:

{{ partialCached "footer.html" . .Section }}

Pass additional arguments, of any data type, as needed to create unique variants:

{{ partialCached "footer.html" . .Params.country .Params.province }}

The variant arguments are not available to the underlying partial template; they are only used to create unique cache keys.

最莫名其妙的地方出現了。講了一堆注意事項就是不講怎麼用,文檔都過一半了才開始介紹使用方式,誰會這樣寫文檔?

更糟糕的是這段還寫的奇爛無比,說明搭配範例介紹,用超過 10 行換來比我的 3 行版本更不清晰的說明:沒有明確提到講 variant 不存在時會怎樣,要求心領神會,寫這麼長一段實際資訊量只等同於我的第二點說明。

甚至範例只是把開頭的 Syntax partials.IncludeCached LAYOUT CONTEXT [VARIANT...] 重寫一次,這代表 syntax 和範例兩個內容有一個無法提供有效資訊。

To return a value from a partial template, it must contain only one return statement, placed at the end of the template:

{{ $result := "" }}
{{ if math.ModBool . 2 }}
{{ $result = "even" }}
{{ else }}
{{ $result = "odd" }}
{{ end }}
{{ return $result }}

整段廢話,教學 partial 用法,與 partialCached 無關。

算下來整篇文檔只有開頭一般說明和注意事項有用,其他全都是雜訊,還不如不寫。