Ordinal
返回 shortcode 相對於其父級的從零開始的序號。
Syntax
SHORTCODE.Ordinal
Returns
int
Ordinal 方法返回 shortcode 相對於其父級的從零開始的序號。如果父級是頁面本身,序號表示此 shortcode 在頁面內容中的位置。
Hugo 在每個 shortcode 調用時遞增序號,無論具體的 shortcode 類型如何。這意味著序號值在給定頁面內的所有 shortcode 中按順序跟蹤。
此方法對於在從同一頁面調用 shortcode 兩次或更多次時分配唯一元素 ID 很有用。例如:
content/about.md
{{< img src="images/a.jpg" >}}
{{< img src="images/b.jpg" >}}此 shortcode 執行錯誤檢查,然後渲染帶有唯一 id 屬性的 HTML img 元素:
layouts/_shortcodes/img.html
{{ $src := "" }}
{{ with .Get "src" }}
{{ $src = . }}
{{ with resources.Get $src }}
{{ $id := printf "img-%03d" $.Ordinal }}
<img id="{{ $id }}" src="{{ .RelPermalink }}" width="{{ .Width }}" height="{{ .Height }}" alt="">
{{ else }}
{{ errorf "The %q shortcode was unable to find %s. See %s" $.Name $src $.Position }}
{{ end }}
{{ else }}
{{ errorf "The %q shortcode requires a 'src' argument. See %s" .Name .Position }}
{{ end }}Hugo 將頁面渲染為:
<img id="img-000" src="/images/a.jpg" width="600" height="400" alt="">
<img id="img-001" src="/images/b.jpg" width="600" height="400" alt="">在上面的 shortcode 模板中,with 語句用於創建條件塊。請記住,with 語句將上下文(點)綁定到其表達式。在 with 塊內,在 shortcode 方法調用前加上 $ 以訪問傳遞給模板的頂級上下文。