序号
语法
SHORTCODE.Ordinal
返回
int
Ordinal
方法返回短代码相对于其父级的从零开始的序号。如果父级是页面本身,则序号表示此短代码在页面内容中的位置。
此方法对于(尤其)在同一页面多次调用短代码时分配唯一的元素 ID 非常有用。例如
content/about.md
{{< img src="images/a.jpg" >}}
{{< img src="images/b.jpg" >}}
此短代码执行错误检查,然后使用唯一的 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="">