complement

将以下英文翻译为中文:

complement

https://gohugo.io/functions/complement/

Returns the elements of the last collection that are not in any of the others.

语法

complement COLLECTION [COLLECTION]...
collections.Complement COLLECTION [COLLECTION]...

To find the elements within $c3 that do not exist in $c1 or $c2:

1
2
3
4
5
{{ $c1 := slice 3 }}
{{ $c2 := slice 4 5 }}
{{ $c3 := slice 1 2 3 4 5 }}

{{ complement $c1 $c2 $c3 }} → [1 2]

Make your code simpler to understand by using a chained pipeline:

1
{{ $c3 | complement $c1 $c2 }} → [1 2]

You can also use the complement function with page collections. Let’s say your site has five content types:

1
2
3
4
5
6
content/
├── blog/
├── books/
├── faqs/
├── films/
└── songs/

To list everything except blog articles (blog) and frequently asked questions (faqs):

1
2
3
4
5
{{ $blog := where site.RegularPages "Type" "blog" }}
{{ $faqs := where site.RegularPages "Type" "faqs" }}
{{ range site.RegularPages | complement $blog $faqs }}
  <a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a>
{{ end }}

Although the example above demonstrates the complement function, you could use the where function as well:

1
2
3
{{ range where site.RegularPages "Type" "not in" (slice "blog" "faqs") }}
  <a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a>
{{ end }}

In this example we use the complement function to remove stop words from a sentence:

1
2
3
4
5
{{ $text := "The quick brown fox jumps over the lazy dog" }}
{{ $stopWords := slice "a" "an" "in" "over" "the" "under" }}
{{ $filtered := split $text " " | complement $stopWords }}

{{ delimit $filtered " " }} → The quick brown fox jumps lazy dog

另请参阅