collections.Append
Syntax
COLLECTION | collections.Append ELEMENT [ELEMENT...]
COLLECTION | collections.Append COLLECTION
Returns
any
Alias
append
该函数将所有元素(最后一个元素除外)追加到最后一个元素中。这允许使用如下所示的管道构造。
将单个元素追加到切片中:
{{ $s := slice "a" "b" }}
{{ $s }} → [a b]
{{ $s = $s | append "c" }}
{{ $s }} → [a b c]
将两个元素追加到切片中:
{{ $s := slice "a" "b" }}
{{ $s }} → [a b]
{{ $s = $s | append "c" "d" }}
{{ $s }} → [a b c d]
将两个元素作为切片追加到切片中。这将产生与前一个示例相同的结果:
{{ $s := slice "a" "b" }}
{{ $s }} → [a b]
{{ $s = $s | append (slice "c" "d") }}
{{ $s }} → [a b c d]
从一个空切片开始:
{{ $s := slice }}
{{ $s }} → []
{{ $s = $s | append "a" }}
{{ $s }} → [a]
{{ $s = $s | append "b" "c" }}
{{ $s }} → [a b c]
{{ $s = $s | append (slice "d" "e") }}
{{ $s }} → [a b c d e]
如果你从一个切片的切片开始:
{{ $s := slice (slice "a" "b") }}
{{ $s }} → [[a b]]
{{ $s = $s | append (slice "c" "d") }}
{{ $s }} → [[a b] [c d]]
通过从一个空切片开始创建切片的切片:
{{ $s := slice }}
{{ $s }} → []
{{ $s = $s | append (slice (slice "a" "b")) }}
{{ $s }} → [[a b]]
{{ $s = $s | append (slice "c" "d") }}
{{ $s }} → [[a b] [c d]]
尽管上面的示例中的元素是字符串,但你可以将append
函数与任何数据类型一起使用,包括页面(Pages)。例如,在企业网站的主页上,显示链接到两个最新的新闻稿,然后是链接到最近四个文章:
{{ $p := where site.RegularPages "Type" "press-releases" | first 2 }}
{{ $p = $p | append (where site.RegularPages "Type" "articles" | first 4) }}
{{ with $p }}
<ul>
{{ range . }}
<li><a href="{{ .RelPermalink }}">{{ .Title }}</a></li>
{{ end }}
</ul>
{{ end }}