HUGO
Menu
GitHub 87548 stars Mastodon

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 方法调用前加上 $ 以访问传递给模板的顶级上下文。


Last updated: January 1, 0001
Improve this page