HUGO
News Docs Themes Community GitHub

Get

Returns a slice of weighted pages to which the given term has been assigned.

Syntax

TAXONOMY.Get TERM

Returns

page.WeightedPages

The Get method on a Taxonomy object returns a slice of weighted pages to which the given term has been assigned.

Before we can use a Taxonomy method, we need to capture a Taxonomy object.

Capture a Taxonomy object

Consider this site configuration:

taxonomies:
  author: authors
  genre: genres
[taxonomies]
  author = 'authors'
  genre = 'genres'
{
   "taxonomies": {
      "author": "authors",
      "genre": "genres"
   }
}

And this content structure:

content/
├── books/
│   ├── and-then-there-were-none.md --> genres: suspense
│   ├── death-on-the-nile.md        --> genres: suspense
│   └── jamaica-inn.md              --> genres: suspense, romance
│   └── pride-and-prejudice.md      --> genres: romance
└── _index.md

To capture the “genres” Taxonomy object from within any template, use the Taxonomies method on a Site object.

{{ $taxonomyObject := .Site.Taxonomies.genres }}

To capture the “genres” Taxonomy object when rendering its page with a taxonomy template, use the Terms method on the page’s Data object:

layouts/_default/taxonomy.html
{{ $taxonomyObject := .Data.Terms }}

To inspect the data structure:

<pre>{{ debug.Dump $taxonomyObject }}</pre>

Although the Alphabetical and ByCount methods provide a better data structure for ranging through the taxonomy, you can render the weighted pages by term directly from the Taxonomy object:

{{ range $term, $weightedPages := $taxonomyObject }}
  <h2><a href="{{ .Page.RelPermalink }}">{{ .Page.LinkTitle }}</a></h2>
  <ul>
    {{ range $weightedPages }}
      <li><a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a></li>
    {{ end }}
  </ul>
{{ end }}

In the example above, the first anchor element is a link to the term page.

Get the weighted pages

Now that we have captured the “genres” Taxonomy object, let’s get the weighted pages to which the “suspense” term has been assigned:

{{ $weightedPages := $taxonomyObject.Get "suspense" }}

The above is equivalent to:

{{ $weightedPages := $taxonomyObject.suspense }}

But, if the term is not a valid identifier, you cannot use the chaining syntax. For example, this will throw an error because the identifier contains a hyphen:

{{ $weightedPages := $taxonomyObject.my-genre }}

You could also use the index function, but the syntax is more verbose:

{{ $weightedPages := index $taxonomyObject "my-genre" }}

To inspect the data structure:

<pre>{{ debug.Dump $weightedPages }}</pre>

Example

With this template:

{{ $weightedPages := $taxonomyObject.Get "suspense" }}
{{ range $weightedPages }}
  <h2><a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a></h2>
{{ end }}

Hugo renders:

<h2><a href="/books/jamaica-inn/">Jamaica inn</a></h2>
<h2><a href="/books/death-on-the-nile/">Death on the nile</a></h2>
<h2><a href="/books/and-then-there-were-none/">And then there were none</a></h2>