Hugo Templating

Variables

Page Variables

Official Documentation

Below page collections can be accessed from any scope in the templates:

  • .Site.Pages - all pages of the site: regular pages, sections, taxonomies, etc.
  • .Site.RegularPages - only regular pages.

Below variables return pages from the scope of the current list page:

  • .Pages - regular pages and first-level section pages under the current list page.
  • .RegularPages - only regular pages under the current list page, excluding regular pages in nested sections/list pages.
  • .RegularPagesRecursive - all regular pages under a list page, including regular pages in nested sections/list pages
VariableDescription
.Aliasesaliases of this page
.AlternativeOutputFormatscontains all alternative formats for a given page; this variable is especially useful link rel list in your site’s <head>. (See Output Formats .)
.Contentcontent itself, defined below the front matter.
.Datadata specific to this type of page.
.Datedate associated with the page; .Date pulls from the date field in a content’s front matter. See also .ExpiryDate, .PublishDate, and .Lastmod.
.Descriptiondescription for the page.
.Dirpath of the folder containing this content file. The path is relative to the content folder.
.Draftboolean, true if the content is marked as a draft in the front matter.
.ExpiryDatedate on which the content is scheduled to expire; .ExpiryDate pulls from the expirydate field in a content’s front matter. See also .PublishDate, .Date, and .Lastmod.
.Filefilesystem-related data for this content file. See also File Variables .
.FuzzyWordCountapproximate number of words in the content.
.Hugosee Hugo Variables .
.IsHometrue in the context of the homepage .
.IsNodealways false for regular content pages.
.IsPagealways true for regular content pages.
.IsSectiontrue if .Kind is section.
.IsTranslatedtrue if there are translations to display.
.Keywordsmeta keywords for the content.
.Kindpage’s kind. Possible return values are page, home, section, taxonomy, or taxonomyTerm. Note that there are also RSS, sitemap, robotsTXT, and 404 kinds, but these are only available during the rendering of each of these respective page’s kind and therefore not available in any of the Pages collections.
.Languagelanguage object that points to the language’s definition in the site config. .Language.Lang gives you the language code.
.Lastmoddate the content was last modified. .Lastmod pulls from the lastmod field in a content’s front matter. If lastmod is not set, and .GitInfo feature is disabled, the front matter date field will be used. If lastmod is not set, and .GitInfo feature is enabled, .GitInfo.AuthorDate will be used instead. See also .ExpiryDate, .Date, .PublishDate, and .GitInfo .
.LinkTitleaccess when creating links to the content. If set, Hugo will use the linktitle from the front matter before title.
.NextPoints up to the next regular page (sorted by Hugo’s default sort ). Example: {{with **.Next**}}{{.Permalink}}{{end}}. Calling .Next from the first page returns nil.
.NextInSectionPoints up to the next regular page below the same top level section (e.g. in /blog)). Pages are sorted by Hugo’s default sort . Example: {{with **.NextInSection**}}{{.Permalink}}{{end}}. Calling .NextInSection from the first page returns nil.
.OutputFormatscontains all formats, including the current format, for a given page. Can be combined the with .Get function to grab a specific format. (See Output Formats .)
.Pagescollection of associated pages. This value will be nil within the context of regular content pages. See .Pages .
.PermalinkPermanent link for this page; see Permalinks
.PlainPage content stripped of HTML tags and presented as a string.
.PlainWordsslice of strings that results from splitting .Plain into words, as defined in Go’s strings.Fields .
.PrevPoints down to the previous regular page (sorted by Hugo’s default sort ). Example: {{if **.Prev**}}{{.Prev.Permalink}}{{end}}. Calling .Prev from the last page returns nil.
.PrevInSectionPoints down to the previous regular page below the same top level section (e.g. /blog). Pages are sorted by Hugo’s default sort . Example: {{if **.PrevInSection**}}{{.PrevInSection.Permalink}}{{end}}. Calling .PrevInSection from the last page returns nil.
.PublishDatedate on which the content was or will be published; .Publishdate pulls from the publishdate field in a content’s front matter. See also .ExpiryDate, .Date, and .Lastmod.
.RSSLink (deprecated)link to the page’s RSS feed. This is deprecated. You should instead do something like this: {{ with **.OutputFormats**.Get "RSS" }}{{ **.RelPermalink** }}{{ end }}.
.RawContentraw markdown content without the front matter. Useful with remarkjs.com
.ReadingTimeestimated time, in minutes, it takes to read the content.
.Refreturns the permalink for a given reference (.Ref "sample.md"). .Ref does not handle in-page fragments correctly. See Cross References .
.RegularPagesCollection of only regular pages under the current list page. This excludes regular pages in nested sections/list pages (those are subdirectories with an _index.md file.
.RegularPagesRecursiveCollection of all regular pages under a list page. This includes regular pages in nested sections/list pages.
.RelPermalinkrelative permanent link for this page.
.RelRefreturns the relative permalink for a given reference (RelRef "sample.md"). .RelRef does not handle in-page fragments correctly. See Cross References .
.Resourcesresources such as images and CSS that are associated with this page
.Sitesee Site Variables .
.Sitesreturns all sites (languages). A typical use case would be to link back to the main language: <a href="{{ **.Sites**.First.Home.RelPermalink }}">...</a>.
.Sites.Firstreturns the site for the first language. If this is not a multilingual setup, it will return itself.
.Summarygenerated summary of the content for easily showing a snippet in a summary view. The breakpoint can be set manually by inserting <!-- more--> at the appropriate place in the content page, or the summary can be written independent of the page text. See Content Summaries for more details.
.TableOfContentsrendered table of contents for the page.
.Titletitle for this page.
.TranslationKeykey used to map language translations of the current page. See Multilingual Mode for more information.
.Translationslist of translated versions of the current page. See Multilingual Mode for more information.
.Truncatedboolean, true if the .Summary is truncated. Useful for showing a “Read more…” link only when necessary. See Summaries for more information.
.Typecontent type of the content (posts).
.Weightassigned weight (in the front matter) to this content, used in sorting.
.WordCountnumber of words in the content.
.UniqueID (deprecated)MD5-checksum of the content file’s path. This variable is deprecated and will be removed, use .File.UniqueID instead.

File Variables

Official Hugo Documentation

The .File object contains the following fields:

VariableDescription
.File.Paththe original relative path of the page, relative to the content dir (e.g., posts/foo.en.md)
.File.LogicalNamethe name of the content file that represents a page (e.g., foo.en.md)
.File.TranslationBaseNamethe filename without extension or optional language identifier (e.g., foo)
.File.ContentBaseNameis a either TranslationBaseName or name of containing folder if file is a leaf bundle.
.File.BaseFileNamethe filename without extension (e.g., foo.en)
.File.Extthe file extension of the content file (e.g., md); this can also be called using .File.Extension as well. Note that it is only the extension without ..
.File.Langthe language associated with the given file if Hugo’s Multilingual features are enabled (e.g., en)
.File.Dirgiven the path content/posts/dir1/dir2/, the relative directory path of the content file will be returned (e.g., posts/dir1/dir2/). Note that the path separator (\ or /) could be dependent on the operating system.
.File.UniqueIDthe MD5-checksum of the content file’s path.

Site Variables

Official Documentation

VariableDescription
.Site.AllPagesarray of all pages, regardless of their translation.
.Site.Authora map of the authors as defined in the site configuration.
.Site.BaseURLthe base URL for the site as defined in the site configuration.
.Site.BuildDraftsa boolean (default: false) to indicate whether to build drafts as defined in the site configuration.
.Site.Copyrighta string representing the copyright of your website as defined in the site configuration.
.Site.Datacustom data, see Data Templates.
.Site.DisqusShortnamea string representing the shortname of the Disqus shortcode as defined in the site configuration.
.Site.GoogleAnalyticsa string representing your tracking code for Google Analytics as defined in the site configuration.
.Site.Homereference to the homepage’s page object
.Site.IsMultiLingualwhether there are more than one language in this site. See Multilingual for more information.
.Site.IsServera boolean to indicate if the site is being served with Hugo’s built-in server. See hugo server for more information.
.Site.Language.Langthe language code of the current locale (e.g., en).
.Site.Language.LanguageNamethe full language name (e.g. English).
.Site.Language.Weightthe weight that defines the order in the .Site.Languages list.
.Site.Languageindicates the language currently being used to render the website. This object’s attributes are set in site configurations' language definition.
.Site.LanguageCodea string representing the language as defined in the site configuration. This is mostly used to populate the RSS feeds with the right language code.
.Site.LanguagePrefixthis can be used to prefix URLs to point to the correct language. It will even work when only one defined language. See also the functions absLangURL and relLangURL.
.Site.Languagesan ordered list (ordered by defined weight) of languages.
.Site.LastChangea string representing the date/time of the most recent change to your site. This string is based on the date variable in the front matter of your content pages.
.Site.Menusall of the menus in the site.
.Site.Pagesarray of all content ordered by Date with the newest first. This array contains only the pages in the current language. See .Site.Pages.
.Site.RegularPagesa shortcut to the regular page collection. .Site.RegularPages is equivalent to where .Site.Pages “Kind” “page”. See .Site.Pages.
.Site.Sectionstop-level directories of the site.
.Site.Taxonomiesthe taxonomies for the entire site. Also see section Taxonomies elsewhere.
.Site.Titlea string representing the title of the site.

Section Variables

Official Documentation

Also see Sections

  • .Sections - all sections below the content
  • .Section - the section that the content belongs to
  • .Parent - A section’s parent section or a page’s section.
  • .CurrentSection - The page’s current section. The value can be the page itself if it is a section or the homepage.
  • .FirstSection- The page’s first section below root, e.g. /docs, /blog etc.
  • .NextInSection - Next regular page in the same section
  • .InSection $page - Whether the given page is in the current section.
  • .IsAncestor $page - Whether the current page is an ancestor of the given page.
  • .IsDescendant $page - Whether the current page is a descendant of the given page.
VariableDescription
.CurrentSectionpage’s current section. The value can be the page itself if it is a section or the homepage.
.FirstSectionpage’s first section below root, e.g. /docs, /blog etc.
.InSection $anotherPageWhether the given page is in the current section.
.IsAncestor $anotherPageWhether the current page is an ancestor of the given page.
.IsDescendant $anotherPageWhether the current page is a descendant of the given page.
.Parentsection’s parent section or a page’s section.
.Sectionsection this content belongs to. Note: For nested sections, this is the first path element in the directory, for example, /blog/funny/mypost/ => blog.
.Sectionssections below this content.

^(\.(\w+))+\n(.*)

Content Lists

Hugo provides example partials for list templates.

List all site menus

List site menus as defined in menus.yaml

{{ range .Site.Menus.main }}
<a href="{{ .URL }}" class="...">{{ .Name }}</a>
{{ end }}

List all pages

{{ range .Site.Sections }}
<a href="{{ .RelPermalink }}" class="...">{{ .Title }}</a>
{{ end }}

Pages without param

Iterates over all regular pages and excludes pages with either:

  1. hidden set to true, or
  2. pages with no hidden param.
{{ $hidden_pages := where .Site.RegularPages "Params.hidden" true }} {{ $pages := .Site.RegularPages | complement
$hidden_pages }}

List all site tags

<ul>
  {{ range .Site.Taxonomies.tags }}
  <li>
    <a href="{{ .Page.Permalink }}">{{ .Page.Title }}</a>
    {{ .Count }}
  </li>
  {{ end }}
</ul>

List pages in a series

<!-- using .Site.Taxonomies  -->
<ul>
  {{ range .Site.Taxonomies.series.hugo }}
  <li><a href="{{ .Page.RelPermalink }}">{{ .Page.Title }}</a></li>
  {{ end }}
</ul>

<!-- using filter -->
{{ range where .Site.Pages "Params.series" "hugo" }} {{ .Content }} {{ end }}

List pages with summary

<h1>{{ .Title }}</h1>
<!-- ranges through each of the content files associated with a particular taxonomy term and renders the summary.html content view -->
{{ range .Pages }} {{ .Render "summary"}} {{ end }}

List page categories

{{ if .Params.categories }} {{- range $index, $value := (.GetTerms "categories") -}} {{- if gt $index 0 }}, {{ end -}}
<a href="{{ .RelPermalink }}">{{- humanize .LinkTitle -}}</a>
{{- end -}} {{ end }}

List subsections of a section

{{ range (where .Site.Pages "Section" "docs") }}
<ul>
  {{ range .Sections }}
  <li><a href="{{ .Permalink}}">{{ .LinkTitle }}</a></li>
  {{end}}
</ul>
{{ end }}

List pages in a section if there is at least one page

{{ $pages := where .Site.RegularPages "Section" "docs" }} {{ $count := len $pages }} {{ if gt $count 0 }} ... {{ end }}

source

List pages in a section with a given param

<!--Pages in the "docs" section with a "summary" param -->
{{ $docs := where .Site.RegularPages "Section" "docs" }} {{ $pages := where $docs "Params.type" "summary" }}

<!-- Pages in the "docs" section where "drafts" = false -->
{{$pages := where (where .Site.RegularPages "Section" "docs") ".Params.draft" false }}

List pages in a section with options

{{ range ((where .Pages ".Params.draft" false).ByParam "order").Reverse }}

Functions

See Functions Quick Reference in the official Hugo docs

Logic Checks

<!-- syntax: -->
{{
<operator>
  <val1><val2>}}</val2></val1>
</operator>
<!-- if... else -->
{{ if }} ... {{ else }} ... {{ end }}

<!-- arg1 == arg2 -->
{{ if eq arg1 arg2 }}

<!-- arg1 != arg2 -->
{{ if ne arg1 arg2 }}

<!-- arg1 < arg2 -->
{{ if lt arg1 arg2 }}

<!-- arg1 > arg2 -->
{{ if gt arg1 arg2 }}

<!-- arg0 < arg1 < arg2 -->
{{ if and (lt arg1 arg2) (gt arg1 arg0) }}

source

Strings

Replace character in string

{{ replace $tag "_" " "}}

Conditionals

source: Hugo docs

if, else, with, or, and and provide the framework for handling conditional logic in Go Templates. Like range, each statement is closed with an {{ end }}.

Go Templates treat the following values as false:

  • false (boolean)
  • 0 (integer)
  • any zero-length array, slice, map, or string

Partial Templates

Hugo’s partial templates are HTML template snippets that can be reused throughout the site’s layout templates. Partial templates should be placed within layouts/partials/.

Shortcodes

Shortcodes enable access to HTML templates snippets from within markdown files. Hugo ships with built-in shortcodes and has support for custom shortcodes . Custom shortcodes should be placed within layouts/shortcodes.

Get parameter by name

{{ .Get "parameter" }}

Get parameter by position

{{ .Get 0 }}

Output based on parameter

{{ with .Get "class" }} class="{{ . }}"{{ end }}

Paired shortcodes

Use {{ .Inner }} to access content sandwiched in paired shortcodes.

{{< alert note >}}
This is a note.
{{< /alert >}}

Escape shortcodes

source: liatas.com

{{</* myshortcode */>}}

Assets and Styles

Importing Google fonts

@import url('https://fonts.googleapis.com/css2?family=Cousine&family=Lato&family=Lora&display=swap');

Template Lookup Order

Official Documentation

Layout Lookup for Section Pages

  1. layouts/posts/posts.html
  2. layouts/posts/section.html
  3. layouts/posts/list.html
  4. layouts/section/posts.html
  5. layouts/section/section.html
  6. layouts/section/list.html
  7. layouts/_default/posts.html
  8. layouts/_default/section.html
  9. layouts/_default/list.html

Layout Lookup for Term Pages

  1. layouts/categories/term.html
  2. layouts/categories/category.html
  3. layouts/categories/taxonomy.html
  4. layouts/categories/list.html
  5. layouts/term/term.html
  6. layouts/term/category.html
  7. layouts/term/taxonomy.html
  8. layouts/term/list.html
  9. layouts/taxonomy/term.html
  10. layouts/taxonomy/category.html
  11. layouts/taxonomy/taxonomy.html
  12. layouts/taxonomy/list.html
  13. layouts/category/term.html
  14. layouts/category/category.html
  15. layouts/category/taxonomy.html
  16. layouts/category/list.html
  17. layouts/layouts/layouts/layouts/layouts/_default/term.html
  18. layouts/_default/category.html
  19. layouts/_default/taxonomy.html
  20. layouts/_default/list.html

Related