Merge commit '8b9803425e63e1b1801f8d5d676e96368d706722'

This commit is contained in:
Bjørn Erik Pedersen
2024-06-21 09:41:24 +02:00
475 changed files with 7408 additions and 4720 deletions

View File

@@ -1,7 +1,7 @@
---
title: Custom 404 page
linkTitle: 404 page
description: If you know how to create a single page template, you have unlimited options for creating a custom 404.
linkTitle: 404 template
description: Create a template to render a 404 error page.
categories: [templates]
keywords: ['404',page not found]
menu:
@@ -11,45 +11,43 @@ menu:
weight: 220
---
When using Hugo with [GitHub Pages](https://pages.github.com/), you can provide your own template for a [custom 404 error page](https://docs.github.com/en/pages/getting-started-with-github-pages/creating-a-custom-404-page-for-your-github-pages-site) by creating a 404.html template file in the root of your `layouts` folder. When Hugo generates your site, the `404.html` file will be placed in the root.
404 pages will have all the regular [page variables][pagevars] available to use in the templates.
In addition to the standard page variables, the 404 page has access to all site content accessible from `.Pages`.
```txt
▾ layouts/
404.html
```
## 404.html
This is a basic example of a 404.html template:
To render a 404 error page in the root of your site, create a 404 template in the root of the layouts directory. For example:
{{< code file=layouts/404.html >}}
{{ define "main" }}
<main id="main">
<div>
<h1 id="title"><a href="{{ "" | relURL }}">Go Home</a></h1>
</div>
</main>
<h1>404 Not Found</h1>
<p>The page you requested cannot be found.</p>
<p>
<a href="{{ .Site.Home.RelPermalink }}">
Return to the home page
</a>
</p>
{{ end }}
{{< /code >}}
## Automatic loading
For multilingual sites, add the language key to the file name:
Your 404.html file can be set to load automatically when a visitor enters a mistaken URL path, dependent upon the web serving environment you are using. For example:
```text
layouts/
├── 404.de.html
├── 404.en.html
└── 404.fr.html
```
* [GitHub Pages](/hosting-and-deployment/hosting-on-github/), [GitLab Pages](/hosting-and-deployment/hosting-on-gitlab/) and [Cloudflare Pages](/hosting-and-deployment/hosting-on-cloudflare-pages/). The 404 page is automatic.
* Apache. You can specify `ErrorDocument 404 /404.html` in an `.htaccess` file in the root of your site.
* Nginx. You might specify `error_page 404 /404.html;` in your `nginx.conf` file. [Details here](https://nginx.org/en/docs/http/ngx_http_core_module.html#error_page).
* Amazon AWS S3. When setting a bucket up for static web serving, you can specify the error file from within the S3 GUI.
* Amazon CloudFront. You can specify the page in the Error Pages section in the CloudFront Console. [Details here](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/custom-error-pages.html)
* Caddy Server. Use the `handle_errors` directive to specify error pages for one or more status codes. [Details here](https://caddyserver.com/docs/caddyfile/directives/handle_errors)
* Netlify. Add `/* /404.html 404` to `content/_redirects`. [Details Here](https://www.netlify.com/docs/redirects/#custom-404)
* Azure Static Web App. set `responseOverrides.404.rewrite` and `responseOverrides.404.statusCode` in configfile `staticwebapp.config.json`. [Details here](https://docs.microsoft.com/en-us/azure/static-web-apps/configuration#response-overrides)
* Azure Storage as Static Web Site Hosting. You can specify the `Error document path` in the Static website configuration page of the Azure portal. [Details here](https://docs.microsoft.com/en-us/azure/storage/blobs/storage-blob-static-website).
* DigitalOcean App Platform. You can specify `error_document` in your app specification file or use control panel to set up error document. [Details here](https://docs.digitalocean.com/products/app-platform/how-to/manage-static-sites/#configure-a-static-site).
* [Firebase Hosting](https://firebase.google.com/docs/hosting/full-config#404): `/404.html` automatically gets used as the 404 page.
Your production server redirects the browser to the 404 page when a page is not found. Capabilities and configuration vary by host.
[pagevars]: /variables/page/
Host|Capabilities and configuration
:--|:--
Amazon CloudFront|See [details](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/GeneratingCustomErrorResponses.html).
Amazon S3|See [details](https://docs.aws.amazon.com/AmazonS3/latest/userguide/CustomErrorDocSupport.html).
Apache|See [details](https://httpd.apache.org/docs/2.4/custom-error.html).
Azure Static Web Apps|See [details](https://learn.microsoft.com/en-us/azure/static-web-apps/configuration#response-overrides).
Azure Storage|See [details](https://learn.microsoft.com/en-us/azure/storage/blobs/storage-blob-static-website#setting-up-a-static-website).
Caddy|See [deatils](https://caddyserver.com/docs/caddyfile/directives/handle_errors).
Cloudflare Pages|See [details](https://developers.cloudflare.com/pages/configuration/serving-pages/#not-found-behavior).
DigitalOcean App Platform|See [details](https://docs.digitalocean.com/products/app-platform/how-to/manage-static-sites/#configure-a-static-site).
Firebase|See [details](https://firebase.google.com/docs/hosting/full-config#404).
GitHub Pages|Redirection to is automatic and not configurable.
GitLab Pages|See [details](https://docs.gitlab.com/ee/user/project/pages/introduction.html#custom-error-codes-pages).
NGINX|See [details](https://nginx.org/en/docs/http/ngx_http_core_module.html#error_page).
Netlify|See [details](https://docs.netlify.com/routing/redirects/redirect-options/).

View File

@@ -1,12 +1,12 @@
---
title: Templates
linkTitle: Overview
linkTitle: In this section
description: Go templating, template types and lookup order, shortcodes, and data.
categories: []
keywords: []
menu:
docs:
identifier: templates-overview
identifier: templates-in-this-section
parent: templates
weight: 10
weight: 10

View File

@@ -91,7 +91,7 @@ The following shows how you can override both the `"main"` and `"title"` block a
{{ end }}
{{< /code >}}
[hugolists]: /templates/lists
[hugolists]: /templates/lists/
[lookup]: /templates/lookup-order/
[rendering the section]: /templates/section-templates/
[singletemplate]: /templates/single-page-templates/

View File

@@ -1,177 +0,0 @@
---
title: Data templates
description: In addition to Hugo's built-in variables, you can specify your own custom data in templates or shortcodes that pull from both local and dynamic sources.
categories: [templates]
keywords: [data,dynamic,csv,json,toml,yaml,xml]
menu:
docs:
parent: templates
weight: 150
weight: 150
toc: true
aliases: [/extras/datafiles/,/extras/datadrivencontent/,/doc/datafiles/]
---
Hugo supports loading data from YAML, JSON, XML, and TOML files located in the `data` directory at the root of your Hugo project.
{{< youtube FyPgSuwIMWQ >}}
## The data directory
The `data` directory should store additional data for Hugo to use when generating your site.
Data files are not for generating standalone pages. They should supplement content files by:
- Extending the content when the front matter fields grow out of control, or
- Showing a larger dataset in a template (see the example below).
In both cases, it's a good idea to outsource the data in their (own) files.
These files must be YAML, JSON, XML, or TOML files (using the `.yml`, `.yaml`, `.json`, `.xml`, or `.toml` extension). The data will be accessible as a `map` in the `.Site.Data` variable.
To access the data using the `site.Data.filename` notation, the file name must begin with an underscore or a Unicode letter, followed by zero or more underscores, Unicode letters, or Unicode digits. For example:
- `123.json` - Invalid
- `x123.json` - Valid
- `_123.json` - Valid
To access the data using the [`index`](/functions/collections/indexfunction) function, the file name is irrelevant. For example:
Data file|Template code
:--|:--
`123.json`|`{{ index .Site.Data "123" }}`
`x123.json`|`{{ index .Site.Data "x123" }}`
`_123.json`|`{{ index .Site.Data "_123" }}`
`x-123.json`|`{{ index .Site.Data "x-123" }}`
## Data files in themes
Data Files can also be used in themes.
However, note that the theme data files are merged with the project directory taking precedence. That is, Given two files with the same name and relative path, the data in the file in the root project `data` directory will override the data from the file in the `themes/<THEME>/data` directory *for keys that are duplicated*).
Therefore, theme authors should be careful not to include data files that could be easily overwritten by a user who decides to [customize a theme][customize]. For theme-specific data items that shouldn't be overridden, it can be wise to prefix the folder structure with a namespace; e.g. `mytheme/data/<THEME>/somekey/...`. To check if any such duplicate exists, run hugo with the `-v` flag.
The keys in the map created with data templates from data files will be a dot-chained set of `path`, `filename`, and `key` in the file (if applicable).
This is best explained with an example:
## Examples
### Jaco Pastorius' Solo Discography
[Jaco Pastorius](https://en.wikipedia.org/wiki/Jaco_Pastorius_discography) was a great bass player, but his solo discography is short enough to use as an example. [John Patitucci](https://en.wikipedia.org/wiki/John_Patitucci) is another bass giant.
The example below is a bit contrived, but it illustrates the flexibility of data Files. This example uses TOML as its file format with the two following data files:
* `data/jazz/bass/jacopastorius.toml`
* `data/jazz/bass/johnpatitucci.toml`
`jacopastorius.toml` contains the content below. `johnpatitucci.toml` contains a similar list:
{{< code-toggle file=data/jazz/bass/jacopastorius >}}
discography = [
"1974 - Modern American Music … Period! The Criteria Sessions",
"1974 - Jaco",
"1976 - Jaco Pastorius",
"1981 - Word of Mouth",
"1981 - The Birthday Concert (released in 1995)",
"1982 - Twins I & II (released in 1999)",
"1983 - Invitation",
"1986 - Broadway Blues (released in 1998)",
"1986 - Honestly Solo Live (released in 1990)",
"1986 - Live In Italy (released in 1991)",
"1986 - Heavy'n Jazz (released in 1992)",
"1991 - Live In New York City, Volumes 1-7.",
"1999 - Rare Collection (compilation)",
"2003 - Punk Jazz: The Jaco Pastorius Anthology (compilation)",
"2007 - The Essential Jaco Pastorius (compilation)"
]
{{< /code-toggle >}}
The list of bass players can be accessed via `.Site.Data.jazz.bass`, a single bass player by adding the file name without the suffix, e.g. `.Site.Data.jazz.bass.jacopastorius`.
You can now render the list of recordings for all the bass players in a template:
```go-html-template
{{ range $.Site.Data.jazz.bass }}
{{ partial "artist.html" . }}
{{ end }}
```
And then in the `partials/artist.html`:
```go-html-template
<ul>
{{ range .discography }}
<li>{{ . }}</li>
{{ end }}
</ul>
```
Discover a new favorite bass player? Just add another `.toml` file in the same directory.
### Accessing named values in a data file
Assume you have the following data structure in your `user0123` data file located directly in `data/`:
{{< code-toggle file=data/user0123 >}}
Name: User0123
"Short Description": "He is a **jolly good** fellow."
Achievements:
- "Can create a Key, Value list from Data File"
- "Learns Hugo"
- "Reads documentation"
{{</ code-toggle >}}
You can use the following code to render the `Short Description` in your layout:
```go-html-template
<div>Short Description of {{ .Site.Data.user0123.Name }}: <p>{{ index .Site.Data.user0123 "Short Description" | markdownify }}</p></div>
```
Note the use of the [`markdownify`] function. This will send the description through the Markdown rendering engine.
## Remote data
Retrieve remote data using these template functions:
- [`resources.GetRemote`](/functions/resources/getremote) (recommended)
- [`data.GetCSV`](/functions/data/getcsv)
- [`data.GetJSON`](/functions/data/getjson)
## LiveReload with data files
There is no chance to trigger a [LiveReload] when the content of a URL changes. However, when a *local* file changes (i.e., `data/*` and `themes/<THEME>/data/*`), a LiveReload will be triggered. Symlinks are not supported. Note too that because downloading data takes a while, Hugo stops processing your Markdown files until the data download has been completed.
{{% note %}}
If you change any local file and the LiveReload is triggered, Hugo will read the data-driven (URL) content from the cache. If you have disabled the cache (i.e., by running the server with `hugo server --ignoreCache`), Hugo will re-download the content every time LiveReload triggers. This can create *huge* traffic. You may reach API limits quickly.
{{% /note %}}
## Examples of data-driven content
- Photo gallery JSON powered: [https://github.com/pcdummy/hugo-lightslider-example](https://github.com/pcdummy/hugo-lightslider-example)
- GitHub Starred Repositories [in a post](https://github.com/SchumacherFM/blog-cs/blob/master/content%2Fposts%2Fgithub-starred.md) using data-driven content in a [custom short code](https://github.com/SchumacherFM/blog-cs/blob/master/layouts%2Fshortcodes%2FghStarred.html).
## Specs for data formats
* [TOML Spec][toml]
* [YAML Spec][yaml]
* [JSON Spec][json]
* [CSV Spec][csv]
* [XML Spec][xml]
[config]: /getting-started/configuration/
[csv]: https://tools.ietf.org/html/rfc4180
[customize]: /hugo-modules/theme-components/
[json]: https://www.ecma-international.org/publications/files/ECMA-ST/ECMA-404.pdf
[LiveReload]: /getting-started/usage/#livereload
[lookup]: /templates/lookup-order/
[`markdownify`]: /functions/transform/markdownify
[OAuth]: https://en.wikipedia.org/wiki/OAuth
[partials]: /templates/partials/
[toml]: https://toml.io/en/latest
[variadic]: https://en.wikipedia.org/wiki/Variadic_function
[vars]: /variables/
[yaml]: https://yaml.org/spec/
[xml]: https://www.w3.org/XML/

View File

@@ -0,0 +1,223 @@
---
title: Embedded templates
description: Hugo provides embedded templates for common use cases.
categories: [templates]
keywords: [internal, analytics,]
menu:
docs:
parent: templates
weight: 190
weight: 190
toc: true
aliases: [/templates/internal]
---
## Disqus
{{% note %}}
To override Hugo's embedded Disqus template, copy the [source code] to a file with the same name in the layouts/partials directory, then call it from your templates using the [`partial`] function:
`{{ partial "disqus.html" . }}`
[`partial`]: /functions/partials/include/
[source code]: {{% eturl disqus %}}
{{% /note %}}
Hugo includes an embedded template for [Disqus], a popular commenting system for both static and dynamic websites. To effectively use Disqus, secure a Disqus "shortname" by [signing up] for the free service.
[Disqus]: https://disqus.com
[signing up]: https://disqus.com/profile/signup/
To include the embedded template:
```go-html-template
{{ template "_internal/disqus.html" . }}
```
### Configure Disqus
To use Hugo's Disqus template, first set up a single configuration value:
{{< code-toggle file="hugo" >}}
[services.disqus]
shortname = 'your-disqus-shortname'
{{</ code-toggle >}}
Hugo's Disqus template accesses this value with:
```go-html-template
{{ .Site.Config.Services.Disqus.Shortname }}
```
You can also set the following in the front matter for a given piece of content:
- `disqus_identifier`
- `disqus_title`
- `disqus_url`
## Google Analytics
{{% note %}}
To override Hugo's embedded Google Analytics template, copy the [source code] to a file with the same name in the layouts/partials directory, then call it from your templates using the [`partial`] function:
`{{ partial "google_analytics.html" . }}`
[`partial`]: /functions/partials/include/
[source code]: {{% eturl google_analytics %}}
{{% /note %}}
Hugo includes an embedded template supporting [Google Analytics 4].
[Google Analytics 4]: https://support.google.com/analytics/answer/10089681
To include the embedded template:
```go-html-template
{{ template "_internal/google_analytics.html" . }}
```
### Configure Google Analytics
Provide your tracking ID in your configuration file:
{{< code-toggle file=hugo >}}
[services.googleAnalytics]
ID = "G-MEASUREMENT_ID"
{{</ code-toggle >}}
To use this value in your own template, access the configured ID with `{{ site.Config.Services.GoogleAnalytics.ID }}`.
## Open Graph
{{% note %}}
To override Hugo's embedded Open Graph template, copy the [source code] to a file with the same name in the layouts/partials directory, then call it from your templates using the [`partial`] function:
`{{ partial "opengraph.html" . }}`
[`partial`]: /functions/partials/include/
[source code]: {{% eturl opengraph %}}
{{% /note %}}
Hugo includes an embedded template for the [Open Graph protocol](https://ogp.me/), metadata that enables a page to become a rich object in a social graph.
This format is used for Facebook and some other sites.
To include the embedded template:
```go-html-template
{{ template "_internal/opengraph.html" . }}
```
### Configure Open Graph
Hugo's Open Graph template is configured using a mix of configuration settings and [front matter](/content-management/front-matter/) on individual pages.
{{< code-toggle file=hugo >}}
[params]
description = 'Text about my cool site'
images = ['site-feature-image.jpg']
title = 'My cool site'
[params.social]
facebook_admin = 'jsmith'
[taxonomies]
series = 'series'
{{</ code-toggle >}}
{{< code-toggle file=content/blog/my-post.md fm=true >}}
title = "Post title"
description = "Text about this post"
date = 2024-03-08T08:18:11-08:00
images = ["post-cover.png"]
audio = []
videos = []
series = []
tags = []
{{</ code-toggle >}}
Hugo uses the page title and description for the title and description metadata.
The first 6 URLs from the `images` array are used for image metadata.
If [page bundles](/content-management/page-bundles/) are used and the `images` array is empty or undefined, images with file names matching `*feature*` or `*cover*,*thumbnail*` are used for image metadata.
Various optional metadata can also be set:
- Date, published date, and last modified data are used to set the published time metadata if specified.
- `audio` and `videos` are URL arrays like `images` for the audio and video metadata tags, respectively.
- The first 6 `tags` on the page are used for the tags metadata.
- The `series` taxonomy is used to specify related "see also" pages by placing them in the same series.
If using YouTube this will produce a og:video tag like `<meta property="og:video" content="url">`. Use the `https://youtu.be/<id>` format with YouTube videos (example: `https://youtu.be/qtIqKaDlqXo`).
## Schema
{{% note %}}
To override Hugo's embedded Schema template, copy the [source code] to a file with the same name in the layouts/partials directory, then call it from your templates using the [`partial`] function:
`{{ partial "schema.html" . }}`
[`partial`]: /functions/partials/include/
[source code]: {{% eturl schema %}}
{{% /note %}}
Hugo includes an embedded template to render [microdata] `meta` elements within the `head` element of your templates.
[microdata]: https://html.spec.whatwg.org/multipage/microdata.html#microdata
To include the embedded template:
```go-html-template
{{ template "_internal/schema.html" . }}
```
## X (Twitter) Cards
{{% note %}}
To override Hugo's embedded Twitter Cards template, copy the [source code] to a file with the same name in the layouts/partials directory, then call it from your templates using the [`partial`] function:
`{{ partial "twitter_cards.html" . }}`
[`partial`]: /functions/partials/include/
[source code]: {{% eturl twitter_cards %}}
{{% /note %}}
Hugo includes an embedded template for [X (Twitter) Cards](https://developer.x.com/en/docs/twitter-for-websites/cards/overview/abouts-cards),
metadata used to attach rich media to Tweets linking to your site.
To include the embedded template:
```go-html-template
{{ template "_internal/twitter_cards.html" . }}
```
### Configure X (Twitter) Cards
Hugo's X (Twitter) Card template is configured using a mix of configuration settings and [front-matter](/content-management/front-matter/) values on individual pages.
{{< code-toggle file=hugo >}}
[params]
images = ["site-feature-image.jpg"]
description = "Text about my cool site"
{{</ code-toggle >}}
{{< code-toggle file=content/blog/my-post.md >}}
title = "Post title"
description = "Text about this post"
images = ["post-cover.png"]
{{</ code-toggle >}}
If `images` aren't specified in the page front-matter, then hugo searches for [image page resources](/content-management/image-processing/) with `feature`, `cover`, or `thumbnail` in their name.
If no image resources with those names are found, the images defined in the [site config](/getting-started/configuration/) are used instead.
If no images are found at all, then an image-less Twitter `summary` card is used instead of `summary_large_image`.
Hugo uses the page title and description for the card's title and description fields. The page summary is used if no description is given.
Set the value of `twitter:site` in your site configuration:
{{< code-toggle file="hugo" copy=false >}}
[params.social]
twitter = "GoHugoIO"
{{</ code-toggle >}}
NOTE: The `@` will be added for you
```html
<meta name="twitter:site" content="@GoHugoIO"/>
```

View File

@@ -12,11 +12,8 @@ toc: true
aliases: [/layout/homepage/,/templates/homepage-template/]
---
Homepage is a `Page` and therefore has all the [page variables][pagevars] and [site variables][sitevars] available for use.
{{% note %}}
The homepage template is the *only* required template for building a site and therefore useful when bootstrapping a new site and template. It is also the only required template if you are developing a single-page website.
{{% /note %}}
{{< youtube ut1xtRZ1QOA >}}
@@ -32,8 +29,6 @@ See the homepage template below or [Content Organization][contentorg] for more i
## Example homepage template
The following is an example of a homepage template that uses [partial][partials], [base] templates, and a content file at `content/_index.md` to populate the `{{ .Title }}` and `{{ .Content }}` [page variables][pagevars].
{{< code file=layouts/index.html >}}
{{ define "main" }}
<main aria-role="main">
@@ -56,10 +51,6 @@ The following is an example of a homepage template that uses [partial][partials]
{{ end }}
{{< /code >}}
[base]: /templates/base/
[contentorg]: /content-management/organization/
[lists]: /templates/lists/
[lookup]: /templates/lookup-order/
[pagevars]: /variables/page/
[partials]: /templates/partials/
[sitevars]: /variables/site/

View File

@@ -1,221 +0,0 @@
---
title: Internal templates
description: Hugo ships with a group of boilerplate templates that cover the most common use cases for static websites.
categories: [templates]
keywords: [internal, analytics,]
menu:
docs:
parent: templates
weight: 190
weight: 190
toc: true
---
{{% note %}}
While the following internal templates are called similar to partials, they do *not* observe the partial template lookup order.
{{% /note %}}
## Google Analytics
Hugo ships with an internal template supporting [Google Analytics 4].
[Google Analytics 4]: https://support.google.com/analytics/answer/10089681
### Configure Google Analytics
Provide your tracking ID in your configuration file:
**Google Analytics 4 (gtag.js)**
{{< code-toggle file=hugo >}}
[services.googleAnalytics]
ID = "G-MEASUREMENT_ID"
{{</ code-toggle >}}
### Use the Google Analytics template
Include the Google Analytics internal template in your templates where you want the code to appear:
```go-html-template
{{ template "_internal/google_analytics.html" . }}
```
To create your own template, access the configured ID with `{{ site.Config.Services.GoogleAnalytics.ID }}`.
## Disqus
Hugo also ships with an internal template for [Disqus comments][disqus], a popular commenting system for both static and dynamic websites. To effectively use Disqus, secure a Disqus "shortname" by [signing up for the free service][disqussignup].
### Configure Disqus
To use Hugo's Disqus template, first set up a single configuration value:
{{< code-toggle file="hugo" >}}
[services.disqus]
shortname = 'your-disqus-shortname'
{{</ code-toggle >}}
Hugo's Disqus template accesses this value with:
```go-html-template
{{ .Site.Config.Services.Disqus.Shortname }}
```
You can also set the following in the front matter for a given piece of content:
* `disqus_identifier`
* `disqus_title`
* `disqus_url`
### Use the Disqus template
To add Disqus, include the following line in the templates where you want your comments to appear:
```go-html-template
{{ template "_internal/disqus.html" . }}
```
### Conditional loading of Disqus comments
Users have noticed that enabling Disqus comments when running the Hugo web server on `localhost` (i.e. via `hugo server`) causes the creation of unwanted discussions on the associated Disqus account.
You can create the following `layouts/partials/disqus.html`:
{{< code file=layouts/partials/disqus.html >}}
<div id="disqus_thread"></div>
<script type="text/javascript">
(function() {
// Don't ever inject Disqus on localhost--it creates unwanted
// discussions from 'localhost:1313' on your Disqus account...
if (window.location.hostname == "localhost")
return;
var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
var disqus_shortname = '{{ .Site.Config.Services.Disqus.Shortname }}';
dsq.src = '//' + disqus_shortname + '.disqus.com/embed.js';
(document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
})();
</script>
<noscript>Please enable JavaScript to view the <a href="https://disqus.com/?ref_noscript">comments powered by Disqus.</a></noscript>
<a href="https://disqus.com/" class="dsq-brlink">comments powered by <span class="logo-disqus">Disqus</span></a>
{{< /code >}}
The `if` statement skips the initialization of the Disqus comment injection when you are running on `localhost`.
You can then render your custom Disqus partial template as follows:
```go-html-template
{{ partial "disqus.html" . }}
```
## Open Graph
An internal template for the [Open Graph protocol](https://ogp.me/), metadata that enables a page to become a rich object in a social graph.
This format is used for Facebook and some other sites.
### Configure Open Graph
Hugo's Open Graph template is configured using a mix of configuration variables and [front-matter](/content-management/front-matter/) on individual pages.
{{< code-toggle file=hugo >}}
[params]
title = "My cool site"
images = ["site-feature-image.jpg"]
description = "Text about my cool site"
[taxonomies]
series = "series"
{{</ code-toggle >}}
{{< code-toggle file=content/blog/my-post.md >}}
title = "Post title"
description = "Text about this post"
date = "2006-01-02"
images = ["post-cover.png"]
audio = []
videos = []
series = []
tags = []
{{</ code-toggle >}}
Hugo uses the page title and description for the title and description metadata.
The first 6 URLs from the `images` array are used for image metadata.
If [page bundles](/content-management/page-bundles/) are used and the `images` array is empty or undefined, images with file names matching `*feature*` or `*cover*,*thumbnail*` are used for image metadata.
Various optional metadata can also be set:
- Date, published date, and last modified data are used to set the published time metadata if specified.
- `audio` and `videos` are URL arrays like `images` for the audio and video metadata tags, respectively.
- The first 6 `tags` on the page are used for the tags metadata.
- The `series` taxonomy is used to specify related "see also" pages by placing them in the same series.
If using YouTube this will produce a og:video tag like `<meta property="og:video" content="url">`. Use the `https://youtu.be/<id>` format with YouTube videos (example: `https://youtu.be/qtIqKaDlqXo`).
### Use the Open Graph template
To add Open Graph metadata, include the following line between the `<head>` tags in your templates:
```go-html-template
{{ template "_internal/opengraph.html" . }}
```
## Twitter Cards
An internal template for [Twitter Cards](https://developer.twitter.com/en/docs/twitter-for-websites/cards/overview/abouts-cards),
metadata used to attach rich media to Tweets linking to your site.
### Configure Twitter Cards
Hugo's Twitter Card template is configured using a mix of configuration variables and [front-matter](/content-management/front-matter/) on individual pages.
{{< code-toggle file=hugo >}}
[params]
images = ["site-feature-image.jpg"]
description = "Text about my cool site"
{{</ code-toggle >}}
{{< code-toggle file=content/blog/my-post.md >}}
title = "Post title"
description = "Text about this post"
images = ["post-cover.png"]
{{</ code-toggle >}}
If `images` aren't specified in the page front-matter, then hugo searches for [image page resources](/content-management/image-processing/) with `feature`, `cover`, or `thumbnail` in their name.
If no image resources with those names are found, the images defined in the [site config](/getting-started/configuration/) are used instead.
If no images are found at all, then an image-less Twitter `summary` card is used instead of `summary_large_image`.
Hugo uses the page title and description for the card's title and description fields. The page summary is used if no description is given.
Set the value of `twitter:site` in your site configuration:
{{< code-toggle file="hugo" copy=false >}}
[params.social]
twitter = "GoHugoIO"
{{</ code-toggle >}}
NOTE: The `@` will be added for you
```html
<meta name="twitter:site" content="@GoHugoIO"/>
```
### Use the Twitter Cards template
To add Twitter card metadata, include the following line immediately after the `<head>` element in your templates:
```go-html-template
{{ template "_internal/twitter_cards.html" . }}
```
## The internal templates
The code for these templates is located [here](https://github.com/gohugoio/hugo/tree/master/tpl/tplimpl/embedded/templates).
* `_internal/disqus.html`
* `_internal/google_analytics.html`
* `_internal/opengraph.html`
* `_internal/pagination.html`
* `_internal/schema.html`
* `_internal/twitter_cards.html`
[disqus]: https://disqus.com
[disqussignup]: https://disqus.com/profile/signup/

File diff suppressed because it is too large Load Diff

View File

@@ -34,25 +34,9 @@ The idea of a list page comes from the [hierarchical mental model of the web][me
[![Image demonstrating a hierarchical website sitemap.](site-hierarchy.svg)](site-hierarchy.svg)
## List defaults
### Default templates
Since section lists and taxonomy lists (N.B., *not* [taxonomy terms lists][taxterms]) are both *lists* with regards to their templates, both have the same terminating default of `_default/list.html` or `themes/<THEME>/layouts/_default/list.html` in their lookup order. In addition, both [section lists][sectiontemps] and [taxonomy lists][taxlists] have their own default list templates in `_default`.
See [Template Lookup Order](/templates/lookup-order/) for the complete reference.
## Add content and front matter to list pages
Since v0.18, [everything in Hugo is a `Page`][bepsays]. This means list pages and the homepage can have associated content files (i.e. `_index.md`) that contain page metadata (i.e., front matter) and content.
This new model allows you to include list-specific front matter via `.Params` and also means that list templates (e.g., `layouts/_default/list.html`) have access to all [page variables][pagevars].
{{% note %}}
It is important to note that all `_index.md` content files will render according to a *list* template and not according to a [single page template](/templates/single-page-templates/).
{{% /note %}}
### Example project directory
Add content and front matter to list pages by creating an _index.md file for `home`, `section`, `taxonomy`, and `term` pages.
The following is an example of a typical Hugo project directory's content:
@@ -93,7 +77,7 @@ You can now access this `_index.md`'s' content in your list template:
<header>
<h1>{{ .Title }}</h1>
</header>
<!-- "{{ .Content }}" pulls from the markdown content of the corresponding _index.md -->
<!-- "{{ .Content }}" pulls from the Markdown content of the corresponding _index.md -->
{{ .Content }}
</article>
<ul>
@@ -152,7 +136,13 @@ Using this same `layouts/_default/list.html` template and applying it to the `qu
{{< /code >}}
{{% note %}}
The default behavior of Hugo is to pluralize list titles; hence the inflection of the `quote` section to "Quotes" when called with the `.Title` [page variable](/variables/page/). You can change this via the `pluralizeListTitles` directive in your [site configuration](/getting-started/configuration/).
By default, Hugo capitalizes and pluralizes automatic list titles including section, taxonomy, and term pages. You can disable these transformations by setting [`capitalizeListTitles`] and [`pluralizeListTitles`] in your site configuration.
You can change the capitalization style in your site configuration to one of `ap`, `chicago`, `go`, `firstupper`, or `none`. See [details].
[`capitalizeListTitles`]: /getting-started/configuration/#capitalizelisttitles
[`pluralizeListTitles`]: /getting-started/configuration/#pluralizelisttitles
[details]: /getting-started/configuration/#configure-title-case
{{% /note %}}
## Example list templates
@@ -203,10 +193,10 @@ By default, Hugo sorts page collections by:
3. Page [linkTitle], falling back to page [title]
4. Page file path if the page is backed by a file
[date]: /methods/page/date
[weight]: /methods/page/weight
[linkTitle]: /methods/page/linktitle
[title]: /methods/page/title
[date]: /methods/page/date/
[weight]: /methods/page/weight/
[linkTitle]: /methods/page/linktitle/
[title]: /methods/page/title/
Change the sort order using any of the methods below.
@@ -235,18 +225,16 @@ See the documentation on [`where`] and
[getpage]: /methods/page/getpage/
[homepage]: /templates/homepage/
[mentalmodel]: https://webstyleguide.com/wsg3/3-information-architecture/3-site-structure.html
[pagevars]: /variables/page/
[partials]: /templates/partials/
[RSS 2.0]: https://cyber.harvard.edu/rss/rss.html
[rss]: /templates/rss/
[sections]: /content-management/sections/
[sectiontemps]: /templates/section-templates/
[sitevars]: /variables/site/
[taxlists]: /templates/taxonomy-templates/#taxonomy-list-templates
[taxterms]: /templates/taxonomy-templates/#taxonomy-terms-templates
[taxvars]: /variables/taxonomy/
[taxlists]: /templates/taxonomy-templates/#taxonomy-templates
[taxterms]: /templates/taxonomy-templates/#term-templates
[taxvars]: /methods/taxonomy/
[views]: /templates/views/
[`where`]: /functions/collections/where
[`where`]: /functions/collections/where/
[`first`]: /functions/collections/first/
[main sections]: /methods/site/mainsections
[`time.Format`]: /functions/time/format
[main sections]: /methods/site/mainsections/
[`time.Format`]: /functions/time/format/

View File

@@ -1,6 +1,6 @@
---
title: Menu templates
description: Use menu variables and methods in your templates to render a menu.
description: Create templates to render one or more menus.
categories: [templates]
keywords: [lists,sections,menus]
menu:
@@ -14,7 +14,7 @@ aliases: [/templates/menus/]
## Overview
After [defining menu entries], use [menu variables and methods] to render a menu.
After [defining menu entries], use [menu methods] to render a menu.
Three factors determine how to render a menu:
@@ -82,7 +82,7 @@ Call the partial above, passing a menu ID and the current page in context.
## Page references
Regardless of how you [define menu entries], an entry associated with a page has access to page variables and methods.
Regardless of how you [define menu entries], an entry associated with a page has access to page context.
This simplistic example renders a page parameter named `version` next to each entry's `name`. Code defensively using `with` or `if` to handle entries where (a) the entry points to an external resource, or (b) the `version` parameter is not defined.
@@ -128,5 +128,5 @@ Hugo provides two methods to localize your menu entries. See [multilingual].
[localize the menu entries]: /content-management/multilingual/#menus
[menu entry defined in front matter]: /content-management/menus/#example-front-matter
[menu entry defined in site configuration]: /content-management/menus/#example-site-configuration
[menu variables and methods]: /variables/menu-entry/
[menu and methods]: /methods/menu/
[multilingual]: /content-management/multilingual/#menus

View File

@@ -63,7 +63,7 @@ Given a media type and some additional configuration, you get an **Output Format
This is the full set of Hugo's built-in output formats:
{{< datatable "config" "outputFormats" "name" "mediaType" "path" "baseName" "rel" "protocol" "isPlainText" "isHTML" "noUgly" "permalinkable" >}}
{{< datatable "config" "outputFormats" "_key" "baseName" "isHTML" "isPlainText" "mediaType" "noUgly" "path" "permalinkable" "protocol" "rel" >}}
- A page can be output in as many output formats as you want, and you can have an infinite amount of output formats defined **as long as they resolve to a unique path on the file system**. In the above table, the best example of this is `amp` vs. `html`. `amp` has the value `amp` for `path` so it doesn't overwrite the `html` version; e.g. we can now have both `/index.html` and `/amp/index.html`.
- The `mediaType` must match a defined media type.
@@ -83,40 +83,56 @@ The above example is fictional, but if used for the homepage on a site with `bas
### Configure output formats
The following is the full list of configuration options for output formats and their default values:
mediaType
: this must match the `Type` of a defined media type.
path
: sub path to save the output files.
Use these parameters when configuring an output format:
baseName
: the base file name for the list file names (homepage, etc.). **Default:** `index`.
rel
: can be used to create `rel` values in `link` tags. **Default:** `alternate`.
protocol
: will replace the "http://" or "https://" in your `baseURL` for this output format.
isPlainText
: use Go's plain text templates parser for the templates. **Default:** `false`.
: (`string`) The base name of the published file. Default is `index`.
isHTML
: used in situations only relevant for `HTML`-type formats; e.g., page aliases. **Default:** `false`.
: (`bool`) If `true`, classifies the output format as HTML. Hugo uses this value to determine when to create alias redirects, when to inject the LiveReload script, etc. Default is `false`.
noUgly
: used to turn off ugly URLs If `uglyURLs` is set to `true` in your site. **Default:** `false`.
isPlainText
: (`bool`) If `true`, Hugo parses templates for this output format with Go's [text/template] package instead of the [html/template] package. Default is `false`.
[html/template]: https://pkg.go.dev/html/template
[text/template]: https://pkg.go.dev/text/template
mediaType
: (`string`) The [media type] of the published file. This must match a defined media type, either [built-in](#media-types) or custom.
[media type]: https://en.wikipedia.org/wiki/Media_type
notAlternative
: enable if it doesn't make sense to include this format in an `AlternativeOutputFormats` format listing on `Page` (e.g., with `CSS`). Note that we use the term _alternative_ and not _alternate_ here, as it does not necessarily replace the other format. **Default:** `false`.
: (`bool`) If `true`, excludes this output format from the values returned by the [`AlternativeOutputFormats`] method on a `Page` object. Default is `false`.
[`AlternativeOutputFormats`]: /methods/page/alternativeoutputformats/
noUgly
: (`bool`) If `true`, disables ugly URLs for this output format when `uglyURLs` is `true` in your site configuration. Default is `false`.
path
: (`string`) The path to the directory containing the published files, relative to the root of the publish directory.
permalinkable
: make `.Permalink` and `.RelPermalink` return the rendering Output Format rather than main ([see below](#link-to-output-formats)). This is enabled by default for `HTML` and `AMP`. **Default:** `false`.
: (`bool`) If `true`, the [`Permalink`] and [`RelPermalink`] methods on a `Page` object return the rendering output format rather than main output format ([see below](#link-to-output-formats)). Enabled by default for the `html` and `amp` output formats. Default is `false`.
[`Permalink`]: /methods/page/permalink/
[`RelPermalink`]: /methods/page/relpermalink/
protocol
: (`string`) The protocol (scheme) of the URL for this output format. For example, `https://` or `webcal://`. Default is the scheme of the `baseURL` parameter in your site configuration, typically `https://`.
rel
: (`string`) If provided, you can assign this value to `rel` attributes in `link` elements when iterating over output formats in your templates. Default is `alternate`.
root
: (`bool`) If `true`, files will be published to the root of the publish directory. Default is `false`.
ugly
: (`bool`) If `true`, enables uglyURLs for this output format when `uglyURLs` is `false` in your site configuration. Default is `false`.
weight
: Setting this to a non-zero value will be used as the first sort criteria.
: (`int`) When set to a non-zero value, Hugo uses the `weight` as the first criteria when sorting output formats, falling back to the name of the output format. Lighter items float to the top, while heavier items sink to the bottom. Hugo renders output formats sequentially based on the sort order.
## Output formats for pages
@@ -125,7 +141,7 @@ system.
### Default output formats
Every `Page` has a [`Kind`][page_kinds] attribute, and the default Output
Every `Page` has a [`Kind`] attribute, and the default Output
Formats are set based on that.
{{< code-toggle config=outputs />}}
@@ -162,7 +178,10 @@ outputs:
## List output formats
Each `Page` has both an `.OutputFormats` (all formats, including the current) and an `.AlternativeOutputFormats` variable, the latter of which is useful for creating a `link rel` list in your site's `<head>`:
Each `Page` object has both an [`OutputFormats`] method (all formats, including the current) and an [`AlternativeOutputFormats`] method, the latter of which is useful for creating a `link rel` list in your site's `<head>`:
[`OutputFormats`]: /methods/page/outputformats
[`AlternativeOutputFormats`]: /methods/page/alternativeoutputformats
```go-html-template
{{ range .AlternativeOutputFormats -}}
@@ -172,7 +191,10 @@ Each `Page` has both an `.OutputFormats` (all formats, including the current) an
## Link to output formats
`.Permalink` and `.RelPermalink` on `Page` will return the first output format defined for that page (usually `HTML` if nothing else is defined). This is regardless of the template file they are being called from.
The [`Permalink`] and [`RelPermalink`] methods on a `Page` object return the first output format defined for that page (usually `HTML` if nothing else is defined). This is regardless of the template from which they are called.
[`Permalink`]: /methods/page/permalink
[`RelPermalink`]: /methods/page/relpermalink
__from `single.json.json`:__
```go-html-template
@@ -193,7 +215,7 @@ In order for them to return the output format of the current template file inste
{{ end }}
```
From content files, you can use the [`ref` or `relref` shortcodes](/content-management/shortcodes/#ref-and-relref):
From content files, you can use the `ref` or `relref` shortcodes:
```go-html-template
[Neat]({{</* ref "blog/neat.md" "amp" */>}})
@@ -225,4 +247,4 @@ The partial below is a plain text template . The output format is `csv`, and sin
[lookup order]: /templates/lookup-order/
[media type]: https://en.wikipedia.org/wiki/Media_type
[partials]: /templates/partials/
[page_kinds]: /templates/section-templates/#page-kinds
[`kind`]: /methods/page/kind/

View File

@@ -60,9 +60,16 @@ It is also possible to use the `GroupBy` functions in combination with paginatio
## Build the navigation
The `.Paginator` contains enough information to build a paginator interface.
{{% note %}}
To override Hugo's embedded pagination template, copy the [source code] to a file with the same name in the layouts/partials directory, then call it from your templates using the [`partial`] function:
The easiest way to add this to your pages is to include the built-in template (with `Bootstrap`-compatible styles):
`{{ partial "pagination" . }}`
[`partial`]: /functions/partials/include/
[source code]: {{% eturl pagination %}}
{{% /note %}}
The easiest way to add this to your pages is to include the embedded template:
```go-html-template
{{ template "_internal/pagination.html" . }}
@@ -151,4 +158,4 @@ The pages are built on the following form (`BLANK` means no value):
[`after`]: /functions/collections/after/
[configuration]: /getting-started/configuration/
[lists]: /templates/lists/
[`where`]: /functions/collections/where
[`where`]: /functions/collections/where/

View File

@@ -68,7 +68,7 @@ As shown in the above example directory structure, you can nest your directories
The second argument in a partial call is the variable being passed down. The above examples are passing the `.`, which tells the template receiving the partial to apply the current [context][context].
This means the partial will *only* be able to access those variables. The partial is isolated and *has no access to the outer scope*. From within the partial, `$.Var` is equivalent to `.Var`.
This means the partial will *only* be able to access those variables. The partial is isolated and cannot access the outer scope. From within the partial, `$.Var` is equivalent to `.Var`.
## Returning a value from a partial
@@ -177,6 +177,6 @@ The following `footer.html` partial template is used for [spf13.com](https://spf
[customize]: /hugo-modules/theme-components/
[listtemps]: /templates/lists/
[lookup order]: /templates/lookup-order/
[partialcached]: /functions/partials/includecached
[partialcached]: /functions/partials/includecached/
[singletemps]: /templates/single-page-templates/
[themes]: /themes/

View File

@@ -1,183 +0,0 @@
---
title: Markdown render hooks
linkTitle: Render hooks
description: Render Hooks allow custom templates to override markdown rendering functionality.
categories: [templates]
keywords: [markdown]
toc: true
menu:
docs:
parent: templates
weight: 200
weight: 200
---
Note that this is only supported with the [Goldmark](/getting-started/configuration-markup#goldmark) renderer.
You can override certain parts of the default Markdown rendering to HTML by creating templates with base names `render-{kind}` in `layouts/_default/_markup`.
You can also create type/section specific hooks in `layouts/[type/section]/_markup`, e.g.: `layouts/blog/_markup`.
The hook kinds currently supported are:
* `image`
* `link`
* `heading`
* `codeblock`{{< new-in 0.93.0 >}}
You can define [Output-Format-](/templates/output-formats) and [language-](/content-management/multilingual/)specific templates if needed. Your `layouts` folder may look like this:
```text
layouts/
└── _default/
└── _markup/
├── render-codeblock-bash.html
├── render-codeblock.html
├── render-heading.html
├── render-image.html
├── render-image.rss.xml
└── render-link.html
```
Some use cases for the above:
* Resolve link references using `.GetPage`. This would make links portable as you could translate `./my-post.md` (and similar constructs that would work on GitHub) into `/blog/2019/01/01/my-post/` etc.
* Add `target=_blank` to external links.
* Resolve and [process](/content-management/image-processing/) images.
* Add [header links](https://remysharp.com/2014/08/08/automatic-permalinks-for-blog-posts).
## Render hooks for headings, links and images
### Context passed to `render-link` and `render-image`
The `render-link` and `render-image` templates will receive this context:
Page
: The [Page](/variables/page/) being rendered.
Destination
: The URL.
Title
: The title attribute.
Text
: The rendered (HTML) link text.
PlainText
: The plain variant of the above.
### Context passed to `render-heading`
The `render-heading` template will receive this context:
Page
: The [Page](/variables/page/) being rendered.
Level
: The header level (1--6)
Anchor
: An auto-generated html id unique to the header within the page
Text
: The rendered (HTML) text.
PlainText
: The plain variant of the above.
Attributes (map)
: A map of attributes (e.g. `id`, `class`). Note that this will currently always be empty for links.
The `render-image` templates will also receive:
IsBlock {{< new-in 0.108.0 >}}
: Returns true if this is a standalone image and the configuration option [markup.goldmark.parser.wrapStandAloneImageWithinParagraph](/getting-started/configuration-markup/#goldmark) is disabled.
Ordinal {{< new-in 0.108.0 >}}
: Zero-based ordinal for all the images in the current document.
### Link with title markdown example
```md
[Text](https://www.gohugo.io "Title")
```
Here is a code example for how the render-link.html template could look:
{{< code file=layouts/_default/_markup/render-link.html >}}
<a href="{{ .Destination | safeURL }}"{{ with .Title }} title="{{ . }}"{{ end }}{{ if strings.HasPrefix .Destination "http" }} target="_blank" rel="noopener"{{ end }}>{{ .Text | safeHTML }}</a>
{{< /code >}}
### Image markdown example
```md
![Text](https://gohugo.io/images/hugo-logo-wide.svg "Title")
```
Here is a code example for how the render-image.html template could look:
{{< code file=layouts/_default/_markup/render-image.html >}}
<p class="md__image">
<img src="{{ .Destination | safeURL }}" alt="{{ .Text }}" {{ with .Title }} title="{{ . }}"{{ end }} />
</p>
{{< /code >}}
### Heading link example
Given this template file
{{< code file=layouts/_default/_markup/render-heading.html >}}
<h{{ .Level }} id="{{ .Anchor }}">{{ .Text | safeHTML }} <a href="#{{ .Anchor | safeURL }}"></a></h{{ .Level }}>
{{< /code >}}
And this markdown
```md
### Section A
```
The rendered html will be
```html
<h3 id="section-a">Section A <a href="#section-a"></a></h3>
```
## Render hooks for code blocks
{{< new-in 0.93.0 >}}
You can add a hook template for either all code blocks or for a specific type/language (`bash` in the example below):
```goat { class="black f7" }
layouts
└── _default
└── _markup
└── render-codeblock.html
└── render-codeblock-bash.html
```
The default behavior for these code blocks is to do [Code Highlighting](/content-management/syntax-highlighting/#highlighting-in-code-fences), but since you can pass attributes to these code blocks, they can be used for almost anything. One example would be the built-in [GoAT Diagrams](/content-management/diagrams/#goat-diagrams-ascii) or this [Mermaid Diagram Code Block Hook](/content-management/diagrams/#mermaid-diagrams) example.
The context (the ".") you receive in a code block template contains:
Type (string)
: The type of code block. This will be the programming language, e.g. `bash`, when doing code highlighting.
Attributes (map)
: Attributes passed in from Markdown (e.g. `{ attrName1=attrValue1 attrName2="attr Value 2" }`).
Options (map)
: Chroma highlighting processing options. This will only be filled if `Type` is a known [Chroma Lexer](/content-management/syntax-highlighting/#list-of-chroma-highlighting-languages).
Inner (string)
: The text between the code fences.
Ordinal (integer)
: Zero-based ordinal for all code blocks in the current document.
Page
: The owning `Page`.
Position
: Useful in error logging as it prints the file name and position (linenumber, column), e.g. `{{ errorf "error in code block: %s" .Position }}`.

View File

@@ -18,7 +18,9 @@ To generate a robots.txt file from a template, change the [site configuration]:
enableRobotsTXT = true
{{< /code-toggle >}}
By default, Hugo generates robots.txt using an [internal template][internal].
By default, Hugo generates robots.txt using an [embedded template].
[embedded template]: {{% eturl robots %}}
```text
User-agent: *
@@ -56,4 +58,3 @@ Remember that Hugo copies everything in the [static directory][static] to the ro
{{% /note %}}
[site configuration]: /getting-started/configuration/
[internal]: https://github.com/gohugoio/hugo/blob/master/tpl/tplimpl/embedded/templates/_default/robots.txt

View File

@@ -1,6 +1,6 @@
---
title: RSS templates
description: Use the built-in RSS template, or create your own.
description: Use the embedded RSS template, or create your own.
categories: [templates]
keywords: [rss,xml,templates]
menu:
@@ -25,6 +25,8 @@ term = ['html']
To disable feed generation for all [page kinds]:
[page kinds]: /getting-started/glossary/#page-kind
{{< code-toggle file=hugo >}}
disableKinds = ['rss']
{{< /code-toggle >}}
@@ -65,7 +67,10 @@ Hugo will render this to:
## Custom templates
Override Hugo's [built-in RSS template] by creating one or more of your own, following the naming conventions as shown in the [template lookup order table].
Override Hugo's [embedded RSS template] by creating one or more of your own, following the naming conventions as shown in the [template lookup order].
[embedded RSS template]: {{% eturl rss %}}
[template lookup order]: #template-lookup-order
For example, to use different templates for home, section, taxonomy, and term pages:
@@ -80,10 +85,6 @@ layouts/
RSS templates receive the `.Page` and `.Site` objects in context.
[built-in RSS template]: https://github.com/gohugoio/hugo/blob/master/tpl/tplimpl/embedded/templates/_default/rss.xml
[page kinds]: /getting-started/glossary/#page-kind
[template lookup order table]: #template-lookup-order
## Template lookup order
The table below shows the RSS template lookup order for the different page kinds. The first listing shows the lookup order when running with a theme (`demoTheme`).

View File

@@ -1,7 +1,7 @@
---
title: Section page templates
linkTitle: Section templates
description: Templates used for section pages are **lists** and therefore have all the variables and methods available to list pages.
description: Use section templates to list members of a section.
categories: [templates]
keywords: [lists,sections,templates]
menu:
@@ -21,26 +21,6 @@ To effectively leverage section page templates, you should first understand Hugo
See [Template Lookup](/templates/lookup-order/).
## Page kinds
Every `Page` in Hugo has a `.Kind` attribute.
{{% include "content-management/_common/page-kinds.md" %}}
## `.Site.GetPage` with sections
`Kind` can easily be combined with the [`where`] function in your templates to create kind-specific lists of content. This method is ideal for creating lists, but there are times where you may want to fetch just the index page of a single section via the section's path.
The [`.GetPage` function][getpage] looks up an index page of a given `Kind` and `path`.
You can call `.Site.GetPage` with two arguments: `kind` (one of the valid values
of `Kind` from above) and `kind value`.
Examples:
- `{{ .Site.GetPage "section" "posts" }}`
- `{{ .Site.GetPage "page" "search" }}`
## Example: creating a default section template
{{< code file=layouts/_default/section.html >}}
@@ -69,11 +49,11 @@ The `.Site.GetPage` example that follows assumes the following project directory
.
└── content
├── blog
│ ├── _index.md # "title: My Hugo Blog" in the front matter
│ ├── _index.md <-- title: My Hugo Blog
│ ├── post-1.md
│ ├── post-2.md
│ └── post-3.md
└── events #Note there is no _index.md file in "events"
└── events
├── event-1.md
└── event-2.md
```
@@ -81,7 +61,7 @@ The `.Site.GetPage` example that follows assumes the following project directory
`.Site.GetPage` will return `nil` if no `_index.md` page is found. Therefore, if `content/blog/_index.md` does not exist, the template will output the section name:
```go-html-template
<h1>{{ with .Site.GetPage "section" "blog" }}{{ .Title }}{{ end }}</h1>
<h1>{{ with .Site.GetPage "/blog" }}{{ .Title }}{{ end }}</h1>
```
Since `blog` has a section index page with front matter at `content/blog/_index.md`, the above code will return the following result:
@@ -93,7 +73,7 @@ Since `blog` has a section index page with front matter at `content/blog/_index.
If we try the same code with the `events` section, however, Hugo will default to the section title because there is no `content/events/_index.md` from which to pull content and front matter:
```go-html-template
<h1>{{ with .Site.GetPage "section" "events" }}{{ .Title }}{{ end }}</h1>
<h1>{{ with .Site.GetPage "/events" }}{{ .Title }}{{ end }}</h1>
```
Which then returns the following:
@@ -103,8 +83,8 @@ Which then returns the following:
```
[contentorg]: /content-management/organization/
[getpage]: /methods/page/getpage
[getpage]: /methods/page/getpage/
[lists]: /templates/lists/
[lookup]: /templates/lookup-order/
[`where`]: /functions/collections/where
[`where`]: /functions/collections/where/
[sections]: /content-management/sections/

View File

@@ -1,7 +1,7 @@
---
title: Create your own shortcodes
linkTitle: Shortcode templates
description: You can extend Hugo's built-in shortcodes by creating your own using the same templating syntax as that for single and list pages.
description: You can extend Hugo's embedded shortcodes by creating your own using the same templating syntax as that for single and list pages.
categories: [templates]
keywords: [shortcodes,templates]
menu:
@@ -16,18 +16,18 @@ toc: true
Shortcodes are a means to consolidate templating into small, reusable snippets that you can embed directly inside your content.
{{% note %}}
Hugo also ships with built-in shortcodes for common use cases. (See [Content Management: Shortcodes](/content-management/shortcodes/).)
Hugo also ships with embedded shortcodes for common use cases. (See [Content Management: Shortcodes](/content-management/shortcodes/).)
{{% /note %}}
## Create custom shortcodes
Hugo's built-in shortcodes cover many common, but not all, use cases. Luckily, Hugo provides the ability to easily create custom shortcodes to meet your website's needs.
Hugo's embedded shortcodes cover many common, but not all, use cases. Luckily, Hugo provides the ability to easily create custom shortcodes to meet your website's needs.
{{< youtube Eu4zSaKOY4A >}}
### File location
To create a shortcode, place an HTML template in the `layouts/shortcodes` directory of your [source organization]. Consider the file name carefully since the shortcode name will mirror that of the file but without the `.html` extension. For example, `layouts/shortcodes/myshortcode.html` will be called with either `{{</* myshortcode /*/>}}` or `{{%/* myshortcode /*/%}}`.
To create a shortcode, place an HTML template in the `layouts/shortcodes` directory. Consider the file name carefully since the shortcode name will mirror that of the file but without the `.html` extension. For example, `layouts/shortcodes/myshortcode.html` will be called with either `{{</* myshortcode /*/>}}` or `{{%/* myshortcode /*/%}}`.
You can organize your shortcodes in subdirectories, e.g. in `layouts/shortcodes/boxes`. These shortcodes would then be accessible with their relative path, e.g:
@@ -44,31 +44,31 @@ Shortcode templates have a simple [lookup order]:
1. `/layouts/shortcodes/<SHORTCODE>.html`
2. `/themes/<THEME>/layouts/shortcodes/<SHORTCODE>.html`
### Positional vs. named parameters
### Positional vs. named arguments
You can create shortcodes using the following types of parameters:
You can create shortcodes using the following types of arguments:
* Positional parameters
* Named parameters
* Positional *or* named parameters (i.e, "flexible")
* Positional arguments
* Named arguments
* Positional *or* named arguments
In shortcodes with positional parameters, the order of the parameters is important. If a shortcode has a single required value (e.g., the `youtube` shortcode below), positional parameters work very well and require less typing from content authors.
In shortcodes with positional arguments, the order of the arguments is important. If a shortcode has a single required value, positional arguments require less typing from content authors.
For more complex layouts with multiple or optional parameters, named parameters work best. While less terse, named parameters require less memorization from a content author and can be added in a shortcode declaration in any order.
For more complex layouts with multiple or optional arguments, named arguments work best. While less terse, named arguments require less memorization from a content author and can be added in a shortcode declaration in any order.
Allowing both types of parameters (i.e., a "flexible" shortcode) is useful for complex layouts where you want to set default values that can be easily overridden by users.
Allowing both types of arguments is useful for complex layouts where you want to set default values that can be easily overridden by users.
### Access parameters
### Access arguments
All shortcode parameters can be accessed via the `.Get` method. Whether you pass a key (i.e., string) or a number to the `.Get` method depends on whether you are accessing a named or positional parameter, respectively.
All shortcode arguments can be accessed via the `.Get` method. Whether you pass a string or a number to the `.Get` method depends on whether you are accessing a named or positional argument, respectively.
To access a parameter by name, use the `.Get` method followed by the named parameter as a quoted string:
To access an argument by name, use the `.Get` method followed by the named argument as a quoted string:
```go-html-template
{{ .Get "class" }}
```
To access a parameter by position, use the `.Get` followed by a numeric position, keeping in mind that positional parameters are zero-indexed:
To access an argument by position, use the `.Get` followed by a numeric position, keeping in mind that positional arguments are zero-indexed:
```go-html-template
{{ .Get 0 }}
@@ -80,13 +80,13 @@ For the second position, you would just use:
{{ .Get 1 }}
```
`with` is great when the output depends on a parameter being set:
`with` is great when the output depends on a argument being set:
```go-html-template
{{ with .Get "class" }} class="{{ . }}"{{ end }}
```
`.Get` can also be used to check if a parameter has been provided. This is
`.Get` can also be used to check if a argument has been provided. This is
most helpful when the condition depends on either of the values, or both:
```go-html-template
@@ -95,7 +95,7 @@ most helpful when the condition depends on either of the values, or both:
#### `.Inner`
If a closing shortcode is used, the `.Inner` variable will be populated with the content between the opening and closing shortcodes. To check if `.Inner` contains anything other than white space:
The `.Inner` method returns the content between the opening and closing shortcode tags. To check if `.Inner` returns anything other than whitespace:
```go-html-template
{{ if strings.ContainsNonSpace .Inner }}
@@ -103,35 +103,33 @@ If a closing shortcode is used, the `.Inner` variable will be populated with the
{{ end }}
```
A shortcode with content declared via the `.Inner` variable can also be declared without the content and without the closing tag by using the self-closing syntax:
{{% note %}}
Any shortcode that calls the `.Inner` method must be closed or self-closed. To call a shortcode using the self-closing sytax
```go-html-template
{{</* innershortcode /*/>}}
```
{{% note %}}
Any shortcode that refers to `.Inner` must be closed or self-closed.
{{% /note %}}
#### `.Params`
The `.Params` variable in shortcodes contains the list parameters passed to shortcode for more complicated use cases. You can also access higher-scoped parameters with the following logic:
The `.Params` method in shortcodes returns the arguments passed to the shortcode for more complicated use cases. You can also access higher-scoped arguments with the following logic:
$.Params
: these are the parameters passed directly into the shortcode declaration (e.g., a YouTube video ID)
: these are the arguments passed directly into the shortcode declaration (e.g., a YouTube video ID)
$.Page.Params
: refers to the page's parameters; the "page" in this case refers to the content file in which the shortcode is declared (e.g., a `shortcode_color` field in a content's front matter could be accessed via `$.Page.Params.shortcode_color`).
$.Page.Site.Params
: refers to global variables as defined in your [site's configuration file][config].
$.Site.Params
: refers to parameters defined in your site configuration.
#### `.IsNamedParams`
The `.IsNamedParams` variable checks whether the shortcode declaration uses named parameters and returns a boolean value.
The `.IsNamedParams` method checks whether the shortcode declaration uses named arguments and returns a boolean value.
For example, you could create an `image` shortcode that can take either a `src` named parameter or the first positional parameter, depending on the preference of the content's author. Let's assume the `image` shortcode is called as follows:
For example, you could create an `image` shortcode that can take either a `src` named argument or the first positional argument, depending on the preference of the content's author. Let's assume the `image` shortcode is called as follows:
```go-html-template
{{</* image src="images/my-image.jpg" */>}}
@@ -141,25 +139,23 @@ You could then include the following as part of your shortcode templating:
```go-html-template
{{ if .IsNamedParams }}
<img src="{{ .Get "src" }}" alt="">
<img src="{{ .Get "src" }}" alt="">
{{ else }}
<img src="{{ .Get 0 }}" alt="">
<img src="{{ .Get 0 }}" alt="">
{{ end }}
```
See the [example Vimeo shortcode][vimeoexample] below for `.IsNamedParams` in action.
{{% note %}}
While you can create shortcode templates that accept both positional and named parameters, you *cannot* declare shortcodes in content with a mix of parameter types. Therefore, a shortcode declared like `{{</* image src="images/my-image.jpg" "This is my alt text" */>}}` will return an error.
While you can create shortcode templates that accept both positional and named arguments, you *cannot* declare shortcodes in content with a mix of argument types. Therefore, a shortcode declared like `{{</* image src="images/my-image.jpg" "This is my alt text" */>}}` will return an error.
{{% /note %}}
You can also use the variable `.Page` to access all the normal [page variables][pagevars].
Shortcodes can also be nested. In a nested shortcode, you can access the parent shortcode context with the [`.Parent`] shortcode method. This can be very useful for inheritance of common shortcode parameters from the root.
Shortcodes can also be nested. In a nested shortcode, you can access the parent shortcode context with the [`.Parent`] shortcode method. This can be very useful for inheritance from the root.
### Checking for existence
You can check if a specific shortcode is used on a page by calling `.HasShortcode` in that page template, providing the name of the shortcode. This is sometimes useful when you want to include specific scripts or styles in the header that are only used by that shortcode.
You can check if a specific shortcode is used on a page by calling `.HasShortcode` in that page template, providing the name of the shortcode. This is useful when you want to include specific scripts or styles in the header that are only used by that shortcode.
## Custom shortcode examples
@@ -179,7 +175,7 @@ Let's assume you would like to keep mentions of your copyright year current in y
### Single positional example: `youtube`
Embedded videos are a common addition to Markdown content that can quickly become unsightly. The following is the code used by [Hugo's built-in YouTube shortcode][youtubeshortcode]:
Embedded videos are a common addition to Markdown content. The following is the code used by [Hugo's built-in YouTube shortcode][youtubeshortcode]:
```go-html-template
{{</* youtube 09jf3ow9jfw */>}}
@@ -307,9 +303,9 @@ The rendered output of the HTML example code block will be as follows:
### Nested shortcode: image gallery
Hugo's [`.Parent`] shortcode method provides access to the parent shortcode context when the shortcode in question is called within the context of a *parent* shortcode. This provides an inheritance model for common shortcode parameters.
Hugo's [`.Parent`] shortcode method provides access to the parent shortcode context when the shortcode in question is called within the context of a parent shortcode. This provides an inheritance model.
The following example is contrived but demonstrates the concept. Assume you have a `gallery` shortcode that expects one named `class` parameter:
The following example is contrived but demonstrates the concept. Assume you have a `gallery` shortcode that expects one named `class` argument:
{{< code file=layouts/shortcodes/gallery.html >}}
<div class="{{ .Get "class" }}">
@@ -317,7 +313,7 @@ The following example is contrived but demonstrates the concept. Assume you have
</div>
{{< /code >}}
You also have an `img` shortcode with a single named `src` parameter that you want to call inside of `gallery` and other shortcodes, so that the parent defines the context of each `img`:
You also have an `img` shortcode with a single named `src` argument that you want to call inside of `gallery` and other shortcodes, so that the parent defines the context of each `img`:
{{< code file=layouts/shortcodes/img.html >}}
{{- $src := .Get "src" -}}
@@ -350,19 +346,20 @@ This will output the following HTML. Note how the first two `img` shortcodes inh
## Error handling in shortcodes
Use the [errorf](/functions/fmt/errorf) template function and [`.Position`] shortcode method to get useful error messages in shortcodes:
Use the [`errorf`] template function with the [`Name`] and [`Position`] shortcode methods to generate useful error messages:
```sh
{{< code file=layouts/shortcodes/greeting.html >}}
{{ with .Get "name" }}
<p>Hello, my name is {{ . }}.</p>
{{ else }}
{{ errorf "missing value for parameter 'name': %s" .Position }}
{{ errorf "The %q shortcode requires a 'name' argument. See %s" .Name .Position }}
{{ end }}
```
{{< /code >}}
When the above fails, you will see an `ERROR` log similar to the below:
When the above fails, you will see an `ERROR` message such as:
```sh
ERROR 2018/11/07 10:05:55 missing value for parameter name: "/Users/bep/dev/go/gohugoio/hugo/docs/content/en/variables/shortcodes.md:32:1"
ERROR The "greeting" shortcode requires a 'name' argument. See "/home/user/project/content/_index.md:12:1"
```
## Inline shortcodes
@@ -386,28 +383,23 @@ And once enabled, you can do this in your content files:
The above will print the current date and time.
Note that an inline shortcode's inner content is parsed and executed as a Go text template with the same context as a regular shortcode template.
Note that an inline shortcode's inner content is parsed and executed as a Go text template with the same context as a regular shortcode template.
This means that the current page can be accessed via `.Page.Title` etc. This also means that there are no concept of "nested inline shortcodes".
The same inline shortcode can be reused later in the same content file, with different parameters if needed, using the self-closing syntax:
The same inline shortcode can be reused later in the same content file, with different arguments if needed, using the self-closing syntax:
```go-html-template
{{</* time.inline /*/>}}
```
[basic content files]: /content-management/formats/
[built-in shortcode]: /content-management/shortcodes/
[config]: /getting-started/configuration/
[Content Management: Shortcodes]: /content-management/shortcodes/#using-hugo-s-built-in-shortcodes
[source organization]: /getting-started/directory-structure/
[docsshortcodes]: https://github.com/gohugoio/hugo/tree/master/docs/layouts/shortcodes
[figure]: /content-management/shortcodes/#figure
[hugosc]: /content-management/shortcodes/#using-hugo-s-built-in-shortcodes
[lookup order]: /templates/lookup-order/
[pagevars]: /variables/page/
[`.Parent`]: /methods/shortcode/parent/
[`.Position`]: /methods/shortcode/position/
[spfscs]: https://github.com/spf13/spf13.com/tree/master/layouts/shortcodes
[`errorf`]: /functions/fmt/errorf/
[`Name`]: /methods/shortcode/name/
[`Position`]: /methods/shortcode/position/
[built-in shortcode]: /content-management/shortcodes/
[figure]: /content-management/shortcodes/#figure
[lookup order]: /templates/lookup-order/
[source organization]: /getting-started/directory-structure/
[vimeoexample]: #single-flexible-example-vimeo
[youtubeshortcode]: /content-management/shortcodes/#youtube

View File

@@ -18,12 +18,6 @@ See [Template Lookup](/templates/lookup-order/).
## Example single page templates
Content pages are of the type `page` and will therefore have all the [page variables][pagevars] and [site variables] available to use in their templates.
### `posts/single.html`
This single page template makes use of Hugo [base templates], the [`.Format` function] for dates, the [`.WordCount` page variable][pagevars], and ranges through the single content's specific [taxonomies][pagetaxonomy]. [`with`] is also used to check whether the taxonomies are set in the front matter.
{{< code file=layouts/posts/single.html >}}
{{ define "main" }}
<section id="main">
@@ -77,9 +71,7 @@ To easily generate new instances of a content type (e.g., new `.md` files in a s
[`.format` function]: /methods/time/format/
[front matter]: /content-management/front-matter/
[pagetaxonomy]: /templates/taxonomy-templates/#list-terms-assigned-to-a-page
[pagevars]: /variables/page/
[partials]: /templates/partials/
[section]: /content-management/sections/
[site variables]: /variables/site/
[spf13]: https://spf13.com/
[`with`]: /functions/go-template/with/

View File

@@ -14,29 +14,35 @@ aliases: [/layout/sitemap/,/templates/sitemap/]
## Overview
Hugo's built-in sitemap templates conform to v0.9 of the [sitemap protocol].
Hugo's embedded sitemap templates conform to v0.9 of the [sitemap protocol].
With a monolingual project, Hugo generates a sitemap.xml file in the root of the [`publishDir`] using the built-in [sitemap.xml] template.
With a monolingual project, Hugo generates a sitemap.xml file in the root of the [`publishDir`] using the [embedded sitemap template].
With a multilingual project, Hugo generates:
- A sitemap.xml file in the root of each site (language) using the built-in [sitemap.xml] template
- A sitemap.xml file in the root of the [`publishDir`] using the built-in [sitemapindex.xml] template
- A sitemap.xml file in the root of each site (language) using the [embedded sitemap template]
- A sitemap.xml file in the root of the [`publishDir`] using the [embedded sitemapindex template]
[embedded sitemap template]: {{% eturl sitemap %}}
[embedded sitemapindex template]: {{% eturl sitemapindex %}}
## Configuration
Set the default values for [change frequency] and [priority], and the name of the generated file, in your site configuration.
These are the default sitemap configuration values. They apply to all pages unless overridden in front matter.
{{< code-toggle config=sitemap />}}
changefreq
: How frequently a page is likely to change. Valid values are `always`, `hourly`, `daily`, `weekly`, `monthly`, `yearly`, and `never`. Default is `""` (change frequency omitted from rendered sitemap).
: (`string`) How frequently a page is likely to change. Valid values are `always`, `hourly`, `daily`, `weekly`, `monthly`, `yearly`, and `never`. With the default value of `""` Hugo will omit this field from the sitemap. See [details](https://www.sitemaps.org/protocol.html#changefreqdef).
disable {{< new-in 0.125.0 >}}
: (`bool`) Whether to disable page inclusion. Default is `false`. Set to `true` in front matter to exclude the page.
filename
: The name of the generated file. Default is `sitemap.xml`.
: (`string`) The name of the generated file. Default is `sitemap.xml`.
priority
: The priority of a page relative to any other page on the site. Valid values range from 0.0 to 1.0. Default is `-1` (priority omitted from rendered sitemap).
: (`float`) The priority of a page relative to any other page on the site. Valid values range from 0.0 to 1.0. With the default value of `-1` Hugo will omit this field from the sitemap. See [details](https://www.sitemaps.org/protocol.html#priority).
## Override default values
@@ -46,6 +52,7 @@ Override the default values for a given page in front matter.
title = 'News'
[sitemap]
changefreq = 'weekly'
disable = true
priority = 0.8
{{</ code-toggle >}}
@@ -72,8 +79,4 @@ disableKinds = ['sitemap']
{{</ code-toggle >}}
[`publishDir`]: /getting-started/configuration#publishdir
[change frequency]: <https://www.sitemaps.org/protocol.html#changefreqdef>
[priority]: <https://www.sitemaps.org/protocol.html#priority>
[sitemap protocol]: <https://www.sitemaps.org/protocol.html>
[sitemap.xml]: <https://github.com/gohugoio/hugo/blob/master/tpl/tplimpl/embedded/templates/_default/sitemap.xml>
[sitemapindex.xml]: <https://github.com/gohugoio/hugo/blob/master/tpl/tplimpl/embedded/templates/_default/sitemapindex.xml>

View File

@@ -16,44 +16,28 @@ Hugo includes support for user-defined groupings of content called **taxonomies*
Hugo provides multiple ways to use taxonomies throughout your project templates:
* Order the way content associated with a taxonomy term is displayed in a [taxonomy list template](#taxonomy-list-templates)
* Order the way the terms for a taxonomy are displayed in a [taxonomy terms template](#taxonomy-terms-templates)
* Order the way content associated with a taxonomy term is displayed in a [taxonomy template](#taxonomy-templates)
* Order the way the terms for a taxonomy are displayed in a [term template](#term-templates)
* List a single content's taxonomy terms within a [single page template]
## Taxonomy list templates
## Taxonomy templates
Taxonomy list page templates are lists and therefore have all the variables and methods available to [list pages][lists].
Taxonomy list page templates are lists and therefore have all the methods available to [list pages][lists].
### Taxonomy list template lookup order
### Taxonomy template lookup order
See [Template Lookup](/templates/lookup-order/).
## Taxonomy terms templates
## Term templates
### Taxonomy terms templates lookup order
### Term template lookup order
See [Template Lookup](/templates/lookup-order/).
### Taxonomy methods
A Taxonomy is a `map[string]WeightedPages`.
{{< list-pages-in-section path=/methods/taxonomy/ >}}
.Get TERM
: Returns the WeightedPages for a given term. For example: ;
`site.Taxonomies.tags.Get "tag-a"`.
.Count TERM
: The number of pieces of content assigned to the given term. For example: \
`site.Taxonomies.tags.Count "tag-a"`.
.Alphabetical
: Returns an OrderedTaxonomy (slice) ordered by term.
.ByCount
: Returns an OrderedTaxonomy (slice) ordered by number of entries.
.Reverse
: Returns an OrderedTaxonomy (slice) in reverse order. Must be used with an OrderedTaxonomy.
### OrderedTaxonomy
@@ -102,7 +86,7 @@ type WeightedPages []WeightedPage
## Displaying custom metadata in taxonomy terms templates
If you need to display custom metadata for each taxonomy term, you will need to create a page for that term at `/content/<TAXONOMY>/<TERM>/_index.md` and add your metadata in its front matter, [as explained in the taxonomies documentation](/content-management/taxonomies/#add-custom-metadata-to-a-taxonomy-or-term). Based on the Actors taxonomy example shown there, within your taxonomy terms template, you may access your custom fields by iterating through the variable `.Pages` as such:
If you need to display custom metadata for each taxonomy term, you will need to create a page for that term at `/content/<TAXONOMY>/<TERM>/_index.md` and add your metadata in its front matter, [as explained in the taxonomies documentation](/content-management/taxonomies/#add-custom-metadata-to-a-taxonomy-or-term). Based on the Actors taxonomy example shown there, within your taxonomy terms template, you may access your custom fields by ranging over the page collection returned by the [`Pages`] method:
```go-html-template
<ul>
@@ -217,9 +201,9 @@ To render a comma-delimited list:
## List content with the same taxonomy term
If you are using a taxonomy for something like a series of posts, you can list individual pages associated with the same taxonomy. This is also a quick and dirty method for showing related content:
If you are using a taxonomy for something like a series of posts, you can list individual pages associated with the same term. For example:
### Example: showing content in same series
```go-html-template
<ul>
@@ -233,13 +217,11 @@ If you are using a taxonomy for something like a series of posts, you can list i
This would be very useful in a sidebar as “featured content”. You could even have different sections of “featured content” by assigning different terms to the content.
### Example: grouping "featured" content
```go-html-template
<section id="menu">
<ul>
{{ range $key, $taxonomy := .Site.Taxonomies.featured }}
<li>{{ $key }}</li>
{{ range $term, $taxonomy := .Site.Taxonomies.featured }}
<li>{{ $term }}</li>
<ul>
{{ range $taxonomy.Pages }}
<li><a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a></li>
@@ -252,14 +234,8 @@ This would be very useful in a sidebar as “featured content”. You could even
## Render a site's taxonomies
If you wish to display the list of all keys for your site's taxonomy, you can retrieve them from the [`.Site` variable][sitevars] available on every page.
This may take the form of a tag cloud, a menu, or simply a list.
The following example displays all terms in a site's tags taxonomy:
### Example: list all site tags
```go-html-template
<ul>
{{ range .Site.Taxonomies.tags }}
@@ -267,52 +243,43 @@ The following example displays all terms in a site's tags taxonomy:
{{ end }}
</ul>
```
### Example: list all taxonomies, terms, and assigned content
This example will list all taxonomies and their terms, as well as all the content assigned to each of the terms.
{{< code file=layouts/partials/all-taxonomies.html >}}
<ul>
{{ range $taxonomy, $terms := site.Taxonomies }}
<li>
{{ with site.GetPage $taxonomy }}
<a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a>
{{ end }}
<ul>
{{ range $term, $weightedPages := $terms }}
{{ with .Site.Taxonomies }}
{{ $numberOfTerms := 0 }}
{{ range $taxonomy, $terms := . }}
{{ $numberOfTerms = len . | add $numberOfTerms }}
{{ end }}
{{ if gt $numberOfTerms 0 }}
<ul>
{{ range $taxonomy, $terms := . }}
{{ with $terms }}
<li>
<a href="{{ .Page.RelPermalink }}">{{ .Page.LinkTitle }}</a>
<ul>
{{ range $weightedPages }}
<li><a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a></li>
{{ range $term, $weightedPages := . }}
<li>
<a href="{{ .Page.RelPermalink }}">{{ .Page.LinkTitle }}</a>
<ul>
{{ range $weightedPages }}
<li><a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a></li>
{{ end }}
</ul>
</li>
{{ end }}
</ul>
</li>
{{ end }}
</ul>
</li>
{{ end }}
</ul>
{{ end }}
</ul>
{{ end }}
{{< /code >}}
## `.Site.GetPage` for taxonomies
Because taxonomies are lists, the [`.GetPage` function][getpage] can be used to get all the pages associated with a particular taxonomy term using a terse syntax. The following ranges over the full list of tags on your site and links to each of the individual taxonomy pages for each term without having to use the more fragile URL construction of the ["List All Site Tags" example above](#example-list-all-site-tags):
{{< code file=links-to-all-tags.html >}}
{{ $taxo := "tags" }}
<ul class="{{ $taxo }}">
{{ with ($.Site.GetPage (printf "/%s" $taxo)) }}
{{ range .Pages }}
<li><a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a></li>
{{ end }}
{{ end }}
</ul>
{{< /code >}}
[getpage]: /methods/page/getpage
[`Pages`]: /methods/page/pages/
[getpage]: /methods/page/getpage/
[lists]: /templates/lists/
[renderlists]: /templates/lists/
[single page template]: /templates/single-page-templates/
[sitevars]: /variables/site/

View File

@@ -34,7 +34,7 @@ To create a new view, create a template in each of your different content type d
summary.html
```
Hugo also has support for a default content template to be used in the event that a specific content view template has not been provided for that type. Content views can also be defined in the `_default` directory and will work the same as list and single templates who eventually trickle down to the `_default` directory as a matter of the lookup order.
Hugo also has support for a default content view template to be used in the event that a specific content view template has not been provided for that type. Content views can also be defined in the `_default` directory and will work the same as list and single templates who eventually trickle down to the `_default` directory as a matter of the lookup order.
```txt
▾ layouts/
@@ -46,7 +46,7 @@ Hugo also has support for a default content template to be used in the event tha
## Which template will be rendered?
The following is the [lookup order][lookup] for content views:
The following is the [lookup order] for content views:
1. `/layouts/<TYPE>/<VIEW>.html`
2. `/layouts/_default/<VIEW>.html`
@@ -74,7 +74,7 @@ In this example, `.Render` is passed into the template to call the [render funct
### `summary.html`
Hugo will pass the entire page object to the following `summary.html` view template. (See [Page Variables][pagevars] for a complete list.)
Hugo passes the page object to the following `summary.html` view template.
{{< code file=layouts/_default/summary.html >}}
<article class="post">
@@ -101,13 +101,7 @@ Continuing on the previous example, we can change our render function to use a s
{{< /code >}}
[lists]: /templates/lists/
[lookup]: /templates/lookup-order/
[pagevars]: /variables/page/
[render]: /methods/page/render/
[single]: /templates/single-page-templates/
[spf]: https://spf13.com
[spfsourceli]: https://github.com/spf13/spf13.com/blob/master/layouts/_default/li.html
[spfsourcesection]: https://github.com/spf13/spf13.com/blob/master/layouts/_default/section.html
[spfsourcesummary]: https://github.com/spf13/spf13.com/blob/master/layouts/_default/summary.html
[summaries]: /content-management/summaries/
[taxonomylists]: /templates/taxonomy-templates/