docs: Prepare for new sub tree

See #11925
This commit is contained in:
Bjørn Erik Pedersen
2024-01-27 10:47:28 +01:00
parent 1083bf7c08
commit fc7de7136a
1157 changed files with 0 additions and 64232 deletions

View File

@@ -1,55 +0,0 @@
---
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.
categories: [templates]
keywords: ['404',page not found]
menu:
docs:
parent: templates
weight: 220
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:
{{< code file=layouts/404.html >}}
{{ define "main" }}
<main id="main">
<div>
<h1 id="title"><a href="{{ "" | relURL }}">Go Home</a></h1>
</div>
</main>
{{ end }}
{{< /code >}}
## Automatic loading
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:
* [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.
[pagevars]: /variables/page/

View File

@@ -1,16 +0,0 @@
---
title: Templates
linkTitle: Overview
description: Go templating, template types and lookup order, shortcodes, and data.
categories: []
keywords: []
menu:
docs:
identifier: templates-overview
parent: templates
weight: 10
weight: 10
aliases: [/templates/overview/,/templates/content]
---
A template is an HTML file with [template actions](/getting-started/glossary/#template-action), located within the layouts directory of a project, theme, or module. Visit the topics below, in the order presented, to understand template selection and creation.

View File

@@ -1,97 +0,0 @@
---
title: Base templates and blocks
description: The base and block constructs allow you to define the outer shell of your master templates (i.e., the chrome of the page).
categories: [templates,fundamentals]
keywords: [blocks,base]
menu:
docs:
parent: templates
weight: 40
weight: 40
toc: true
aliases: [/templates/blocks/,/templates/base-templates-and-blocks/]
---
The `block` keyword allows you to define the outer shell of your pages' one or more master template(s) and then fill in or override portions as necessary.
{{< youtube QVOMCYitLEc >}}
## Base template lookup order
The base template lookup order closely follows that of the template it applies to (e.g. `_default/list.html`).
See [Template Lookup Order](/templates/lookup-order/) for details and examples.
## Define the base template
The following defines a simple base template at `_default/baseof.html`. As a default template, it is the shell from which all your pages will be rendered unless you specify another `*baseof.html` closer to the beginning of the lookup order.
{{< code file=layouts/_default/baseof.html >}}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>{{ block "title" . }}
<!-- Blocks may include default content. -->
{{ .Site.Title }}
{{ end }}</title>
</head>
<body>
<!-- Code that all your templates share, like a header -->
{{ block "main" . }}
<!-- The part of the page that begins to differ between templates -->
{{ end }}
{{ block "footer" . }}
<!-- More shared code, perhaps a footer but that can be overridden if need be in -->
{{ end }}
</body>
</html>
{{< /code >}}
## Override the base template
From the above base template, you can define a [default list template][hugolists]. The default list template will inherit all of the code defined above and can then implement its own `"main"` block from:
{{< code file=layouts/_default/list.html >}}
{{ define "main" }}
<h1>Posts</h1>
{{ range .Pages }}
<article>
<h2>{{ .Title }}</h2>
{{ .Content }}
</article>
{{ end }}
{{ end }}
{{< /code >}}
This replaces the contents of our (basically empty) "main" block with something useful for the list template. In this case, we didn't define a `"title"` block, so the contents from our base template remain unchanged in lists.
{{% note %}}
Code that you put outside the block definitions *can* break your layout. This even includes HTML comments. For example:
```go-html-template
<!-- Seemingly harmless HTML comment..that will break your layout at build -->
{{ define "main" }}
...your code here
{{ end }}
```
[See this thread from the Hugo discussion forums.](https://discourse.gohugo.io/t/baseof-html-block-templates-and-list-types-results-in-empty-pages/5612/6)
{{% /note %}}
The following shows how you can override both the `"main"` and `"title"` block areas from the base template with code unique to your [default single page template][singletemplate]:
{{< code file=layouts/_default/single.html >}}
{{ define "title" }}
<!-- This will override the default value set in baseof.html; i.e., "{{ .Site.Title }}" in the original example-->
{{ .Title }} &ndash; {{ .Site.Title }}
{{ end }}
{{ define "main" }}
<h1>{{ .Title }}</h1>
{{ .Content }}
{{ end }}
{{< /code >}}
[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

@@ -1,56 +0,0 @@
---
title: Local file templates
description: Hugo's `readDir` and `readFile` functions make it easy to traverse your project's directory structure and write file contents to your templates.
categories: [templates]
keywords: [files,directories]
menu:
docs:
parent: templates
weight: 180
weight: 180
toc: true
aliases: [/extras/localfiles/,/templates/local-files/]
---
## Traverse local files
With Hugo's [`readDir`] and [`readFile`] template functions, you can traverse your website's files on your server.
## Use `readDir`
The [`readDir`] function returns an array of [`os.FileInfo`] structures. It takes the file's `path` as a single string argument. This path can be to any directory of your website (i.e., as found on your server's file system).
Whether the path is absolute or relative does not matter because---at least for `readDir`---the root of your website (typically `./public/`) in effect becomes both:
1. The file system root
2. The current working directory
## Use `readFile`
The [`readfile`] function reads a file from disk and converts it into a string to be manipulated by other Hugo functions or added as-is. `readFile` takes the file, including path, as an argument passed to the function.
To use the `readFile` function in your templates, make sure the path is relative to your *Hugo project's root directory*:
```go-html-template
{{ readFile "/content/templates/local-file-templates" }}
```
### `readFile` Example: Add a Project File to Content
As `readFile` is a function, it is only available to you in your templates and not your content. However, we can create a simple [shortcode template][sct] that calls `readFile`, passes the first argument through the function, and then allows an optional second argument to send the file through the Markdown processor. The pattern for adding this shortcode to your content will be as follows:
```go-html-template
{{</* readfile file="/path/to/local/file.txt" markdown="true" */>}}
```
{{% note %}}
If you are going to create [custom shortcodes](/templates/shortcode-templates/) with `readFile` for a theme, note that usage of the shortcode will refer to the project root and *not* your `themes` directory.
{{% /note %}}
[called directly in the Hugo docs]: https://github.com/gohugoio/hugoDocs/blob/master/content/en/templates/files.md
[`os.FileInfo`]: https://pkg.go.dev/io/fs#FileInfo
[`readDir`]: /functions/os/readdir
[`readFile`]: /functions/os/readfile
[sc]: /content-management/shortcodes/
[sct]: /templates/shortcode-templates/
[readfilesource]: https://github.com/gohugoio/hugoDocs/blob/master/layouts/shortcodes/readfile.html

View File

@@ -1,65 +0,0 @@
---
title: Homepage template
description: The homepage of a website is often formatted differently than the other pages. For this reason, Hugo makes it easy for you to define your new site's homepage as a unique template.
categories: [templates]
keywords: [homepage]
menu:
docs:
parent: templates
weight: 70
weight: 70
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 >}}
## Homepage template lookup order
See [Template Lookup](/templates/lookup-order/).
## Add content and front matter to the homepage
The homepage, similar to other [list pages in Hugo][lists], accepts content and front matter from an `_index.md` file. This file should live at the root of your `content` folder (i.e., `content/_index.md`). You can then add body copy and metadata to your homepage the way you would any other content file.
See the homepage template below or [Content Organization][contentorg] for more information on the role of `_index.md` in adding content and front matter to list pages.
## 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">
<header class="homepage-header">
<h1>{{ .Title }}</h1>
{{ with .Params.subtitle }}
<span class="subtitle">{{ . }}</span>
{{ end }}
</header>
<div class="homepage-content">
<!-- Note that the content for index.html, as a sort of list page, will pull from content/_index.md -->
{{ .Content }}
</div>
<div>
{{ range first 10 .Site.RegularPages }}
{{ .Render "summary" }}
{{ end }}
</div>
</main>
{{ 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/

View File

@@ -1,672 +0,0 @@
---
title: Templating
linkTitle: Templating
description: Hugo uses Go's `html/template` and `text/template` libraries as the basis for the templating.
categories: [templates,fundamentals]
keywords: [go]
menu:
docs:
parent: templates
weight: 20
weight: 20
toc: true
aliases: [/layouts/introduction/,/layout/introduction/, /templates/go-templates/]
---
{{% note %}}
The following is only a primer on Go Templates. For an in-depth look into Go Templates, check the official [Go docs](https://golang.org/pkg/text/template/).
{{% /note %}}
Go Templates provide an extremely simple template language that adheres to the belief that only the most basic of logic belongs in the template or view layer.
## Basic syntax
Go Templates are HTML files with the addition of [variables][variables] and [functions][functions]. Go Template variables and functions are accessible within `{{ }}`.
### Access a predefined variable
A _predefined variable_ could be a variable already existing in the
current scope (like the `.Title` example in the [Variables](#variables) section below) or a custom variable (like the
`$address` example in that same section).
```go-html-template
{{ .Title }}
{{ $address }}
```
Parameters for functions are separated using spaces. The general syntax is:
```go-html-template
{{ FUNCTION ARG1 ARG2 .. }}
```
The following example calls the `add` function with inputs of `1` and `2`:
```go-html-template
{{ add 1 2 }}
```
#### Methods and fields are accessed via dot notation
Accessing the Page Parameter `bar` defined in a piece of content's [front matter].
```go-html-template
{{ .Params.bar }}
```
#### Parentheses can be used to group items together
```go-html-template
{{ if or (isset .Params "alt") (isset .Params "caption") }} Caption {{ end }}
```
#### A single statement can be split over multiple lines
```go-html-template
{{ if or
(isset .Params "alt")
(isset .Params "caption")
}}
```
#### Raw string literals can include newlines
```go-html-template
{{ $msg := `Line one.
Line two.` }}
```
## Variables
Each Go Template gets a data object. In Hugo, each template is passed
a `Page`. In the below example, `.Title` is one of the elements
accessible in that [`Page` variable][pagevars].
With the `Page` being the default scope of a template, the `Title`
element in current scope (`.` -- "the **dot**") is accessible simply
by the dot-prefix (`.Title`):
```go-html-template
<title>{{ .Title }}</title>
```
Values can also be stored in custom variables and referenced later:
{{% note %}}
The custom variables need to be prefixed with `$`.
{{% /note %}}
```go-html-template
{{ $address := "123 Main St." }}
{{ $address }}
```
Variables can be re-defined using the `=` operator. The example below
prints "Var is Hugo Home" on the home page, and "Var is Hugo Page" on
all other pages:
```go-html-template
{{ $var := "Hugo Page" }}
{{ if .IsHome }}
{{ $var = "Hugo Home" }}
{{ end }}
Var is {{ $var }}
```
Variable names must conform to Go's naming rules for [identifiers][identifier].
## Functions
Go Templates only ship with a few basic functions but also provide a mechanism for applications to extend the original set.
[Hugo template functions][functions] provide additional functionality specific to building websites. Functions are called by using their name followed by the required parameters separated by spaces. Template functions cannot be added without recompiling Hugo.
### Example 1: adding numbers
```go-html-template
{{ add 1 2 }}
<!-- prints 3 -->
```
### Example 2: comparing numbers
```go-html-template
{{ lt 1 2 }}
<!-- prints true (i.e., since 1 is less than 2) -->
```
Note that both examples make use of Go Template's [math][math] functions.
{{% note %}}
There are more boolean operators than those listed in the Hugo docs in the [Go Template documentation](https://golang.org/pkg/text/template/#hdr-Functions).
{{% /note %}}
## Includes
When including another template, you will need to pass it the data that it would
need to access.
{{% note %}}
To pass along the current context, please remember to include a trailing **dot**.
{{% /note %}}
The templates location will always be starting at the `layouts/` directory
within Hugo.
### Partial
The [`partial`][partials] function is used to include _partial_ templates using
the syntax `{{ partial "<PATH>/<PARTIAL>.<EXTENSION>" . }}`.
Example of including a `layouts/partials/header.html` partial:
```go-html-template
{{ partial "header.html" . }}
```
### Template
The `template` function was used to include _partial_ templates
in much older Hugo versions. Now it's useful only for calling
[_internal_ templates][internal templates]. The syntax is `{{ template
"_internal/<TEMPLATE>.<EXTENSION>" . }}`.
{{% note %}}
The available **internal** templates can be found
[here](https://github.com/gohugoio/hugo/tree/master/tpl/tplimpl/embedded/templates).
{{% /note %}}
Example of including the internal `opengraph.html` template:
```go-html-template
{{ template "_internal/opengraph.html" . }}
```
## Logic
Go Templates provide the most basic iteration and conditional logic.
### Iteration
The Go Templates make heavy use of `range` to iterate over a _map_,
_array_, or _slice_. The following are different examples of how to
use `range`.
#### Example 1: using context (`.`)
```go-html-template
{{ range $array }}
{{ . }} <!-- The . represents an element in $array -->
{{ end }}
```
#### Example 2: declaring a variable name for an array element's value
```go-html-template
{{ range $elem_val := $array }}
{{ $elem_val }}
{{ end }}
```
#### Example 3: declaring variable names for an array element's index _and_ value
For an array or slice, the first declared variable will map to each
element's index.
```go-html-template
{{ range $elem_index, $elem_val := $array }}
{{ $elem_index }} -- {{ $elem_val }}
{{ end }}
```
#### Example 4: declaring variable names for a map element's key _and_ value
For a map, the first declared variable will map to each map element's
key.
```go-html-template
{{ range $elem_key, $elem_val := $map }}
{{ $elem_key }} -- {{ $elem_val }}
{{ end }}
```
#### Example 5: conditional on empty _map_, _array_, or _slice_
If the _map_, _array_, or _slice_ passed into the range is zero-length then the else statement is evaluated.
```go-html-template
{{ range $array }}
{{ . }}
{{ else }}
<!-- This is only evaluated if $array is empty -->
{{ end }}
```
### Conditionals
`if`, `else`, `with`, `or`, `and` and `not` provide the framework for handling conditional logic in Go Templates. Like `range`, `if` and `with` statements are closed with an `{{ end }}`.
Go Templates treat the following values as **false**:
- `false` (boolean)
- 0 (integer)
- any zero-length array, slice, map, or string
#### Example 1: `with`
It is common to write "if something exists, do this" kind of
statements using `with`.
{{% note %}}
`with` rebinds the context `.` within its scope (just like in `range`).
{{% /note %}}
It skips the block if the variable is absent, or if it evaluates to
"false" as explained above.
```go-html-template
{{ with .Params.title }}
<h4>{{ . }}</h4>
{{ end }}
```
#### Example 2: `with` .. `else`
Below snippet uses the "description" front-matter parameter's value if
set, else uses the default `.Summary` [Page variable][pagevars]:
```go-html-template
{{ with .Param "description" }}
{{ . }}
{{ else }}
{{ .Summary }}
{{ end }}
```
See the [`.Param` function][param].
#### Example 3: `if`
An alternative (and a more verbose) way of writing `with` is using
`if`. Here, the `.` does not get rebound.
Below example is "Example 1" rewritten using `if`:
```go-html-template
{{ if isset .Params "title" }}
<h4>{{ index .Params "title" }}</h4>
{{ end }}
```
#### Example 4: `if` .. `else`
Below example is "Example 2" rewritten using `if` .. `else`, and using
[`isset`] + `.Params` variable (different from the
[`.Param` **function**][param]) instead:
```go-html-template
{{ if (isset .Params "description") }}
{{ index .Params "description" }}
{{ else }}
{{ .Summary }}
{{ end }}
```
#### Example 5: `if` .. `else if` .. `else`
Unlike `with`, `if` can contain `else if` clauses too.
```go-html-template
{{ if (isset .Params "description") }}
{{ index .Params "description" }}
{{ else if (isset .Params "summary") }}
{{ index .Params "summary" }}
{{ else }}
{{ .Summary }}
{{ end }}
```
#### Example 6: `and` & `or`
```go-html-template
{{ if (and (or (isset .Params "title") (isset .Params "caption")) (isset .Params "attr")) }}
```
## Pipes
One of the most powerful components of Go Templates is the ability to stack actions one after another. This is done by using pipes. Borrowed from Unix pipes, the concept is simple: each pipeline's output becomes the input of the following pipe.
Because of the very simple syntax of Go Templates, the pipe is essential to being able to chain together function calls. One limitation of the pipes is that they can only work with a single value and that value becomes the last parameter of the next pipeline.
A few simple examples should help convey how to use the pipe.
### Example 1: `shuffle`
The following two examples are functionally the same:
```go-html-template
{{ shuffle (seq 1 5) }}
```
```go-html-template
{{ (seq 1 5) | shuffle }}
```
### Example 2: `index`
The following accesses the page parameter called "disqus_url" and escapes the HTML. This example also uses the [`index`] function, which is built into Go Templates:
```go-html-template
{{ index .Params "disqus_url" | html }}
```
### Example 3: `or` with `isset`
```go-html-template
{{ if or (or (isset .Params "title") (isset .Params "caption")) (isset .Params "attr") }}
Stuff Here
{{ end }}
```
Could be rewritten as
```go-html-template
{{ if isset .Params "caption" | or isset .Params "title" | or isset .Params "attr" }}
Stuff Here
{{ end }}
```
## Context (aka "the dot") {#the-dot}
The most easily overlooked concept to understand about Go Templates is
that `{{ . }}` always refers to the **current context**.
- In the top level of your template, this will be the data set made
available to it.
- Inside an iteration, however, it will have the value of the
current item in the loop; i.e., `{{ . }}` will no longer refer to
the data available to the entire page.
If you need to access page-level data (e.g., page parameters set in front
matter) from within the loop, you will likely want to do one of the
following:
### 1. Define a variable independent of context
The following shows how to define a variable independent of the context.
{{< code file=tags-range-with-page-variable.html >}}
{{ $title := .Site.Title }}
<ul>
{{ range .Params.tags }}
<li>
<a href="/tags/{{ . | urlize }}">{{ . }}</a>
- {{ $title }}
</li>
{{ end }}
</ul>
{{< /code >}}
{{% note %}}
Notice how once we have entered the loop (i.e. `range`), the value of `{{ . }}` has changed. We have defined a variable outside the loop (`{{ $title }}`) that we've assigned a value so that we have access to the value from within the loop as well.
{{% /note %}}
### 2. Use `$.` to access the global context
`$` has special significance in your templates. `$` is set to the starting value of `.` ("the dot") by default. This is a [documented feature of Go text/template][dotdoc]. This means you have access to the global context from anywhere. Here is an equivalent example of the preceding code block but now using `$` to grab `.Site.Title` from the global context:
{{< code file=range-through-tags-w-global.html >}}
<ul>
{{ range .Params.tags }}
<li>
<a href="/tags/{{ . | urlize }}">{{ . }}</a>
- {{ $.Site.Title }}
</li>
{{ end }}
</ul>
{{< /code >}}
{{% note %}}
The built-in magic of `$` would cease to work if someone were to mischievously redefine the special character; e.g. `{{ $ := .Site }}`. *Don't do it.* You may, of course, recover from this mischief by using `{{ $ := . }}` in a global context to reset `$` to its default value.
{{% /note %}}
## Whitespace
Go 1.6 includes the ability to trim the whitespace from either side of a Go tag by including a hyphen (`-`) and space immediately beside the corresponding `{{` or `}}` delimiter.
For instance, the following Go Template will include the newlines and horizontal tab in its HTML output:
```go-html-template
<div>
{{ .Title }}
</div>
```
Which will output:
```html
<div>
Hello, World!
</div>
```
Leveraging the `-` in the following example will remove the extra white space surrounding the `.Title` variable and remove the newline:
```go-html-template
<div>
{{- .Title -}}
</div>
```
Which then outputs:
```html
<div>Hello, World!</div>
```
Go considers the following characters _whitespace_:
* space
* horizontal tab
* carriage return
* newline
## Comments
In order to keep your templates organized and share information throughout your team, you may want to add comments to your templates. There are two ways to do that with Hugo.
### Go templates comments
Go Templates support `{{/*` and `*/}}` to open and close a comment block. Nothing within that block will be rendered.
For example:
```go-html-template
Bonsoir, {{/* {{ add 0 + 2 }} */}}Eliott.
```
Will render `Bonsoir, Eliott.`, and not care about the syntax error (`add 0 + 2`) in the comment block.
### HTML comments
You can add html comments by piping a string HTML code comment to `safeHTML`.
For example:
```go-html-template
{{ "<!-- This is an HTML comment -->" | safeHTML }}
```
If you need variables to construct such HTML comments, just pipe `printf` to `safeHTML`.
For example:
```go-html-template
{{ printf "<!-- Our website is named: %s -->" .Site.Title | safeHTML }}
```
#### HTML comments containing Go templates
HTML comments are by default stripped, but their content is still evaluated. That means that although the HTML comment will never render any content to the final HTML pages, code contained within the comment may fail the build process.
{{% note %}}
Do **not** try to comment out Go Template code using HTML comments.
{{% /note %}}
```go-html-template
<!-- {{ $author := "Emma Goldman" }} was a great woman. -->
{{ $author }}
```
The templating engine will strip the content within the HTML comment, but will first evaluate any Go Template code if present within. So the above example will render `Emma Goldman`, as the `$author` variable got evaluated in the HTML comment. But the build would have failed if that code in the HTML comment had an error.
## Hugo parameters
Hugo provides the option of passing values to your template layer through your [site configuration][config] (i.e. for site-wide values) or through the metadata of each specific piece of content (i.e. the [front matter]). You can define any values of any type and use them however you want in your templates, as long as the values are supported by the [front matter format](/content-management/front-matter#front-matter-formats).
## Use content (`Page`) parameters
You can provide variables to be used by templates in individual content's [front matter].
An example of this is used in the Hugo docs. Most of the pages benefit from having the table of contents provided, but sometimes the table of contents doesn't make a lot of sense. We've defined a `notoc` variable in our front matter that will prevent a table of contents from rendering when specifically set to `true`.
Here is the example front matter:
{{< code-toggle file=content/example.md fm=true >}}
title: Example
notoc: true
{{< /code-toggle >}}
Here is an example of corresponding code that could be used inside a `toc.html` [partial template][partials]:
{{< code file=layouts/partials/toc.html >}}
{{ if not .Params.notoc }}
<aside>
<header>
<a href="#{{ .Title | urlize }}">
<h3>{{ .Title }}</h3>
</a>
</header>
{{ .TableOfContents }}
</aside>
<a href="#" id="toc-toggle"></a>
{{ end }}
{{< /code >}}
We want the *default* behavior to be for pages to include a TOC unless otherwise specified. This template checks to make sure that the `notoc:` field in this page's front matter is not `true`.
## Use site configuration parameters
You can arbitrarily define as many site-level parameters as you want in your [site's configuration file][config]. These parameters are globally available in your templates.
For instance, you might declare the following:
{{< code-toggle file=hugo >}}
params:
copyrighthtml: "Copyright &#xA9; 2017 John Doe. All Rights Reserved."
twitteruser: "spf13"
sidebarrecentlimit: 5
{{< /code >}}
Within a footer layout, you might then declare a `<footer>` that is only rendered if the `copyrighthtml` parameter is provided. If it *is* provided, you will then need to declare the string is safe to use via the [`safeHTML`] function so that the HTML entity is not escaped again. This would let you easily update just your top-level configuration file each January 1st, instead of hunting through your templates.
```go-html-template
{{ if .Site.Params.copyrighthtml }}
<footer>
<div class="text-center">{{ .Site.Params.CopyrightHTML | safeHTML }}</div>
</footer>
{{ end }}
```
An alternative way of writing the "`if`" and then referencing the same value is to use [`with`] instead. `with` rebinds the context (`.`) within its scope and skips the block if the variable is absent:
{{< code file=layouts/partials/twitter.html >}}
{{ with .Site.Params.twitteruser }}
<div>
<a href="https://twitter.com/{{ . }}" rel="author">
<img src="/images/twitter.png" width="48" height="48" title="Twitter: {{ . }}" alt="Twitter"></a>
</div>
{{ end }}
{{< /code >}}
Finally, you can pull "magic constants" out of your layouts as well. The following uses the [`first`] function, as well as the [`.RelPermalink`][relpermalink] page variable and the [`.Site.Pages`][sitevars] site variable.
```go-html-template
<nav>
<h1>Recent Posts</h1>
<ul>
{{- range first .Site.Params.SidebarRecentLimit .Site.Pages -}}
<li><a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a></li>
{{- end -}}
</ul>
</nav>
```
## Example: show future events
Given the following content structure and [front matter]:
```text
content/
└── events/
├── event-1.md
├── event-2.md
└── event-3.md
```
{{< code-toggle file=content/events/event-1.md >}}
title = 'Event 1'
date = 2021-12-06T10:37:16-08:00
draft = false
start_date = 2021-12-05T09:00:00-08:00
end_date = 2021-12-05T11:00:00-08:00
{{< /code-toggle >}}
This [partial template][partials] renders future events:
{{< code file=layouts/partials/future-events.html >}}
<h2>Future Events</h2>
<ul>
{{ range where site.RegularPages "Type" "events" }}
{{ if gt (.Params.start_date | time.AsTime) now }}
{{ $startDate := .Params.start_date | time.Format ":date_medium" }}
<li>
<a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a> - {{ $startDate }}
</li>
{{ end }}
{{ end }}
</ul>
{{< /code >}}
If you restrict front matter to the TOML format, and omit quotation marks surrounding date fields, you can perform date comparisons without casting.
{{< code file=layouts/partials/future-events.html >}}
<h2>Future Events</h2>
<ul>
{{ range where (where site.RegularPages "Type" "events") "Params.start_date" "gt" now }}
{{ $startDate := .Params.start_date | time.Format ":date_medium" }}
<li>
<a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a> - {{ $startDate }}
</li>
{{ end }}
</ul>
{{< /code >}}
[`first`]: /functions/collections/first
[`index`]: /functions/collections/indexfunction
[`isset`]: /functions/collections/isset
[config]: /getting-started/configuration
[dotdoc]: https://golang.org/pkg/text/template/#hdr-Variables
[front matter]: /content-management/front-matter
[functions]: /functions
[identifier]: /getting-started/glossary/#identifier
[internal templates]: /templates/internal
[math]: /functions/math
[pagevars]: /variables/page
[param]: /methods/page/param
[partials]: /templates/partials
[relpermalink]: /variables/page
[`safehtml`]: /functions/safe/html
[sitevars]: /variables/site
[variables]: /variables
[`with`]: /functions/go-template/with

View File

@@ -1,252 +0,0 @@
---
title: Lists of content in Hugo
linkTitle: List templates
description: Lists have a specific meaning and usage in Hugo when it comes to rendering your site homepage, section page, taxonomy list, or taxonomy terms list.
categories: [templates]
keywords: [lists,sections,rss,taxonomies,terms]
menu:
docs:
parent: templates
weight: 60
weight: 60
toc: true
aliases: [/templates/list/,/layout/indexes/]
---
## What is a list page template?
{{< youtube 8b2YTSMdMps >}}
A list page template is a template used to render multiple pieces of content in a single HTML page. The exception to this rule is the homepage, which is still a list but has its own [dedicated template][homepage].
Hugo uses the term *list* in its truest sense; i.e. a sequential arrangement of material, especially in alphabetical or numerical order. Hugo uses list templates on any output HTML page where content is traditionally listed:
* [Home page](/templates/homepage)
* [Section pages](/templates/section-templates)
* [Taxonomy pages](/templates/taxonomy-templates)
* [Taxonomy term pages](/templates/taxonomy-templates)
* [RSS feeds](/templates/rss)
* [Sitemaps](/templates/sitemap-template)
For template lookup order, see [Template Lookup](/templates/lookup-order/).
The idea of a list page comes from the [hierarchical mental model of the web][mentalmodel] and is best demonstrated visually:
[![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
The following is an example of a typical Hugo project directory's content:
```txt
.
...
├── content
| ├── posts
| | ├── _index.md
| | ├── post-01.md
| | └── post-02.md
| └── quote
| | ├── quote-01.md
| | └── quote-02.md
...
```
Using the above example, let's assume you have the following in `content/posts/_index.md`:
{{< code file=content/posts/_index.md >}}
---
title: My Go Journey
date: 2017-03-23
publishdate: 2017-03-24
---
I decided to start learning Go in March 2017.
Follow my journey through this new blog.
{{< /code >}}
You can now access this `_index.md`'s' content in your list template:
{{< code file=layouts/_default/list.html >}}
{{ define "main" }}
<main>
<article>
<header>
<h1>{{ .Title }}</h1>
</header>
<!-- "{{ .Content }}" pulls from the markdown content of the corresponding _index.md -->
{{ .Content }}
</article>
<ul>
<!-- Ranges through content/posts/*.md -->
{{ range .Pages }}
<li>
<a href="{{ .RelPermalink }}">{{ .Date.Format "2006-01-02" }} | {{ .LinkTitle }}</a>
</li>
{{ end }}
</ul>
</main>
{{ end }}
{{< /code >}}
This above will output the following HTML:
{{< code file=example.com/posts/index.html >}}
<!--top of your baseof code-->
<main>
<article>
<header>
<h1>My Go Journey</h1>
</header>
<p>I decided to start learning Go in March 2017.</p>
<p>Follow my journey through this new blog.</p>
</article>
<ul>
<li><a href="/posts/post-01/">Post 1</a></li>
<li><a href="/posts/post-02/">Post 2</a></li>
</ul>
</main>
<!--bottom of your baseof-->
{{< /code >}}
### List pages without `_index.md`
You do *not* have to create an `_index.md` file for every list page (i.e. section, taxonomy, taxonomy terms, etc) or the homepage. If Hugo does not find an `_index.md` within the respective content section when rendering a list template, the page will be created but with no `{{ .Content }}` and only the default values for `.Title` etc.
Using this same `layouts/_default/list.html` template and applying it to the `quotes` section above will render the following output. Note that `quotes` does not have an `_index.md` file to pull from:
{{< code file=example.com/quote/index.html >}}
<!--baseof-->
<main>
<article>
<header>
<!-- Hugo assumes that .Title is the name of the section since there is no _index.md content file from which to pull a "title:" field -->
<h1>Quotes</h1>
</header>
</article>
<ul>
<li><a href="https://example.org/quote/quotes-01/">Quote 1</a></li>
<li><a href="https://example.org/quote/quotes-02/">Quote 2</a></li>
</ul>
</main>
<!--baseof-->
{{< /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/).
{{% /note %}}
## Example list templates
### Section template
This list template has been modified slightly from a template originally used in [spf13.com](https://spf13.com/). It makes use of [partial templates][partials] for the chrome of the rendered page rather than using a [base template][base]. The examples that follow also use the [content view templates][views] `li.html` or `summary.html`.
{{< code file=layouts/section/posts.html >}}
{{ partial "header.html" . }}
{{ partial "subheader.html" . }}
<main>
<div>
<h1>{{ .Title }}</h1>
<ul>
<!-- Renders the li.html content view for each content/posts/*.md -->
{{ range .Pages }}
{{ .Render "li" }}
{{ end }}
</ul>
</div>
</main>
{{ partial "footer.html" . }}
{{< /code >}}
### Taxonomy template
{{< code file=layouts/_default/taxonomy.html >}}
{{ define "main" }}
<main>
<div>
<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 }}
</div>
</main>
{{ end }}
{{< /code >}}
## Sort content
By default, Hugo sorts page collections by:
1. Page [weight]
2. Page [date] (descending)
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
Change the sort order using any of the methods below.
{{< list-pages-in-section path=/methods/pages filter=methods_pages_sort filterType=include titlePrefix=. omitElementIDs=true >}}
## Group content
Group your content by field, parameter, or date using any of the methods below.
{{< list-pages-in-section path=/methods/pages filter=methods_pages_group filterType=include titlePrefix=. omitElementIDs=true >}}
## Filtering and limiting lists
Sometimes you only want to list a subset of the available content. A
common is to only display posts from [main sections]
on the blog's homepage.
See the documentation on [`where`] and
[`first`] for further details.
[base]: /templates/base/
[bepsays]: https://bepsays.com/en/2016/12/19/hugo-018/
[directorystructure]: /getting-started/directory-structure/
[`Format` function]: /methods/time/format/
[front matter]: /content-management/front-matter/
[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/
[views]: /templates/views/
[`where`]: /functions/collections/where
[`first`]: /functions/collections/first/
[main sections]: /methods/site/mainsections
[`time.Format`]: /functions/time/format

File diff suppressed because one or more lines are too long

Before

Width:  |  Height:  |  Size: 193 KiB

View File

@@ -1,136 +0,0 @@
---
title: Template lookup order
description: Hugo uses the rules below to select a template for a given page, starting from the most specific.
categories: [templates,fundamentals]
keywords: [templates]
menu:
docs:
parent: templates
weight: 30
weight: 30
toc: true
---
## Lookup rules
Hugo takes the parameters listed below into consideration when choosing a template for a given page. The templates are ordered by specificity. This should feel natural, but look at the table below for concrete examples of the different parameter variations.
Kind
: The page `Kind` (the home page is one). See the example tables below per kind. This also determines if it is a **single page** (i.e. a regular content page. We then look for a template in `_default/single.html` for HTML) or a **list page** (section listings, home page, taxonomy lists, taxonomy terms. We then look for a template in `_default/list.html` for HTML).
Layout
: Can be set in front matter.
Output Format
: See [Custom Output Formats](/templates/output-formats). An output format has both a `name` (e.g. `rss`, `amp`, `html`) and a `suffix` (e.g. `xml`, `html`). We prefer matches with both (e.g. `index.amp.html`), but look for less specific templates.
Note that if the output format's Media Type has more than one suffix defined, only the first is considered.
Language
: We will consider a language tag in the template name. If the site language is `fr`, `index.fr.amp.html` will win over `index.amp.html`, but `index.amp.html` will be chosen before `index.fr.html`.
Type
: Is value of `type` if set in front matter, else it is the name of the root section (e.g. "blog"). It will always have a value, so if not set, the value is "page".
Section
: Is relevant for `section`, `taxonomy` and `term` types.
{{% note %}}
Templates can live in either the project's or the themes' layout folders, and the most specific templates will be chosen. Hugo will interleave the lookups listed below, finding the most specific one either in the project or themes.
{{% /note %}}
## Target a template
You cannot change the lookup order to target a content page, but you can change a content page to target a template. Specify `type`, `layout`, or both in front matter.
Consider this content structure:
```text
content/
├── about.md
└── contact.md
```
Files in the root of the content directory have a [content type] of `page`. To render these pages with a unique template, create a matching subdirectory:
[content type]: /getting-started/glossary/#content-type
```text
layouts/
└── page/
└── single.html
```
But the contact page probably has a form and requires a different template. In the front matter specify `layout`:
{{< code-toggle file=content/contact.md >}}
title = 'Contact'
layout = 'contact'
{{< /code-toggle >}}
Then create the template for the contact page:
```text
layouts/
└── page/
└── contact.html <-- renders contact.md
└── single.html <-- renders about.md
```
As a content type, the word `page` is vague. Perhaps `miscellaneous` would be better. Add `type` to the front matter of each page:
{{< code-toggle file=content/about.md >}}
title = 'About'
type = 'miscellaneous'
{{< /code-toggle >}}
{{< code-toggle file=content/contact.md >}}
title = 'Contact'
type = 'miscellaneous'
layout = 'contact'
{{< /code-toggle >}}
Now place the layouts in the corresponding directory:
```text
layouts/
└── miscellaneous/
└── contact.html <-- renders contact.md
└── single.html <-- renders about.md
```
## Home page
{{< datatable-filtered "output" "layouts" "Kind == home" "Example" "OutputFormat" "Suffix" "Template Lookup Order" >}}
## Single pages
{{< datatable-filtered "output" "layouts" "Kind == page" "Example" "OutputFormat" "Suffix" "Template Lookup Order" >}}
## Section pages
A section page is a list of pages within a given section.
{{< datatable-filtered "output" "layouts" "Kind == section" "Example" "OutputFormat" "Suffix" "Template Lookup Order" >}}
## Taxonomy pages
A taxonomy page is a list of terms within a given taxonomy. The examples below assume the following site configuration:
{{< code-toggle file=hugo >}}
[taxonomies]
category = 'categories'
{{< /code-toggle >}}
{{< datatable-filtered "output" "layouts" "Kind == taxonomy" "Example" "OutputFormat" "Suffix" "Template Lookup Order" >}}
## Term pages
A term page is a list of pages associated with a given term. The examples below assume the following site configuration:
{{< code-toggle file=hugo >}}
[taxonomies]
category = 'categories'
{{< /code-toggle >}}
{{< datatable-filtered "output" "layouts" "Kind == term" "Example" "OutputFormat" "Suffix" "Template Lookup Order" >}}

View File

@@ -1,132 +0,0 @@
---
title: Menu templates
description: Use menu variables and methods in your templates to render a menu.
categories: [templates]
keywords: [lists,sections,menus]
menu:
docs:
parent: templates
weight: 140
weight: 140
toc: true
aliases: [/templates/menus/]
---
## Overview
After [defining menu entries], use [menu variables and methods] to render a menu.
Three factors determine how to render a menu:
1. The method used to define the menu entries: [automatic], [in front matter], or [in site configuration]
1. The menu structure: flat or nested
1. The method used to [localize the menu entries]: site configuration or translation tables
The example below handles every combination.
## Example
This partial template recursively "walks" a menu structure, rendering a localized, accessible nested list.
{{< code file=layouts/partials/menu.html copy=true >}}
{{- $page := .page }}
{{- $menuID := .menuID }}
{{- with index site.Menus $menuID }}
<nav>
<ul>
{{- partial "inline/menu/walk.html" (dict "page" $page "menuEntries" .) }}
</ul>
</nav>
{{- end }}
{{- define "partials/inline/menu/walk.html" }}
{{- $page := .page }}
{{- range .menuEntries }}
{{- $attrs := dict "href" .URL }}
{{- if $page.IsMenuCurrent .Menu . }}
{{- $attrs = merge $attrs (dict "class" "active" "aria-current" "page") }}
{{- else if $page.HasMenuCurrent .Menu .}}
{{- $attrs = merge $attrs (dict "class" "ancestor" "aria-current" "true") }}
{{- end }}
{{- $name := .Name }}
{{- with .Identifier }}
{{- with T . }}
{{- $name = . }}
{{- end }}
{{- end }}
<li>
<a
{{- range $k, $v := $attrs }}
{{- with $v }}
{{- printf " %s=%q" $k $v | safeHTMLAttr }}
{{- end }}
{{- end -}}
>{{ $name }}</a>
{{- with .Children }}
<ul>
{{- partial "inline/menu/walk.html" (dict "page" $page "menuEntries" .) }}
</ul>
{{- end }}
</li>
{{- end }}
{{- end }}
{{< /code >}}
Call the partial above, passing a menu ID and the current page in context.
{{< code file=layouts/_default/single.html >}}
{{ partial "menu.html" (dict "menuID" "main" "page" .) }}
{{ partial "menu.html" (dict "menuID" "footer" "page" .) }}
{{< /code >}}
## Page references
Regardless of how you [define menu entries], an entry associated with a page has access to page variables and methods.
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.
{{< code file=layouts/_default/single.html >}}
{{- range site.Menus.main }}
<a href="{{ .URL }}">
{{ .Name }}
{{- with .Page }}
{{- with .Params.version -}}
({{ . }})
{{- end }}
{{- end }}
</a>
{{- end }}
{{< /code >}}
## Menu entry parameters
When you define menu entries [in site configuration] or [in front matter], you can include a `params` key as shown in these examples:
- [Menu entry defined in site configuration]
- [Menu entry defined in front matter]
This simplistic example renders a `class` attribute for each anchor element. Code defensively using `with` or `if` to handle entries where `params.class` is not defined.
{{< code file=layouts/partials/menu.html >}}
{{- range site.Menus.main }}
<a {{ with .Params.class -}} class="{{ . }}" {{ end -}} href="{{ .URL }}">
{{ .Name }}
</a>
{{- end }}
{{< /code >}}
## Localize
Hugo provides two methods to localize your menu entries. See [multilingual].
[automatic]: /content-management/menus/#define-automatically
[define menu entries]: /content-management/menus/
[defining menu entries]: /content-management/menus/
[in front matter]: /content-management/menus/#define-in-front-matter
[in site configuration]: /content-management/menus/#define-in-site-configuration
[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/
[multilingual]: /content-management/multilingual/#menus

View File

@@ -1,231 +0,0 @@
---
title: Custom output formats
description: Hugo can output content in multiple formats, including calendar events, e-book formats, Google AMP, and JSON search indexes, or any custom text format.
categories: [templates,fundamentals]
keywords: ["amp", "outputs", "rss"]
menu:
docs:
parent: templates
weight: 210
weight: 210
toc: true
aliases: [/templates/outputs/,/extras/output-formats/,/content-management/custom-outputs/]
---
This page describes how to properly configure your site with the media types and output formats, as well as where to create your templates for your custom outputs.
## Media types
A [media type] (formerly known as a MIME type) is a two-part identifier for file formats and format contents transmitted on the internet.
This is the full set of built-in media types in Hugo:
{{< datatable "config" "mediaTypes" "_key" "suffixes" >}}
**Note:**
- It is possible to add custom media types or change the defaults; e.g., if you want to change the suffix for `text/html` to `asp`.
- `Suffixes` are the values that will be used for URLs and file names for that media type in Hugo.
- The `Type` is the identifier that must be used when defining new/custom `Output Formats` (see below).
- The full set of media types will be registered in Hugo's built-in development server to make sure they are recognized by the browser.
To add or modify a media type, define it in a `mediaTypes` section in your [site configuration], either for all sites or for a given language.
{{< code-toggle file=hugo >}}
[mediaTypes]
[mediaTypes."text/enriched"]
suffixes = ["enr"]
[mediaTypes."text/html"]
suffixes = ["asp"]
{{</ code-toggle >}}
The above example adds one new media type, `text/enriched`, and changes the suffix for the built-in `text/html` media type.
**Note:** these media types are configured for **your output formats**. If you want to redefine one of Hugo's default output formats (e.g. `HTML`), you also need to redefine the media type. So, if you want to change the suffix of the `HTML` output format from `html` (default) to `htm`:
{{< code-toggle file=hugo >}}
[mediaTypes]
[mediaTypes."text/html"]
suffixes = ["htm"]
[outputFormats]
[outputFormats.html]
mediaType = "text/html"
{{</ code-toggle >}}
{{% note %}}
For the above to work, you also need to add an `outputs` definition in your site configuration.
{{% /note %}}
## Output format definitions
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" >}}
- 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.
- You can define new output formats or redefine built-in output formats; e.g., if you want to put `amp` pages in a different path.
To add or modify an output format, define it in an `outputFormats` section in your site's [configuration file](/getting-started/configuration/), either for all sites or for a given language.
{{< code-toggle file=hugo >}}
[outputFormats.MyEnrichedFormat]
mediaType = "text/enriched"
baseName = "myindex"
isPlainText = true
protocol = "bep://"
{{</ code-toggle >}}
The above example is fictional, but if used for the homepage on a site with `baseURL` `https://example.org`, it will produce a plain text homepage with the URL `bep://example.org/myindex.enr`.
### Configure output formats
The following is the full list of configuration options for output formats and their default values:
name
: the output format identifier. This is used to define what output format(s) you want for your pages.
mediaType
: this must match the `Type` of a defined media type.
path
: sub path to save the output files.
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`.
isHTML
: used in situations only relevant for `HTML`-type formats; e.g., page aliases. **Default:** `false`.
noUgly
: used to turn off ugly URLs If `uglyURLs` is set to `true` in your site. **Default:** `false`.
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`.
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`.
weight
: Setting this to a non-zero value will be used as the first sort criteria.
## Output formats for pages
A `Page` in Hugo can be rendered to multiple _output formats_ on the file
system.
### Default output formats
Every `Page` has a [`Kind`][page_kinds] attribute, and the default Output
Formats are set based on that.
{{< code-toggle config=outputs />}}
### Customizing output formats
This can be changed by defining an `outputs` list of output formats in either
the `Page` front matter or in the site configuration (either for all sites or
per language).
Example from site configuration file:
{{< code-toggle file=hugo >}}
[outputs]
home = ["html", "amp", "rss"]
page = ["html"]
{{</ code-toggle >}}
Note that in the above examples, the _output formats_ for `section`,
`taxonomy` and `term` will stay at their default value `['html','rss']`.
* The `outputs` definition is per page [`Kind`][page_kinds].
* The names (e.g. `html`, `amp`) must match the `name` of a defined output format, and can be overridden per page in front matter.
The following is an example of front matter in a content file that defines output formats for the rendered `Page`:
{{< code-toggle file=content/example.md fm=true >}}
title: Example
outputs:
- html
- amp
- json
{{< /code-toggle >}}
## 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>`:
```go-html-template
{{ range .AlternativeOutputFormats -}}
<link rel="{{ .Rel }}" type="{{ .MediaType.Type }}" href="{{ .Permalink | safeURL }}">
{{ end }}
```
## 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.
__from `single.json.json`:__
```go-html-template
{{ .RelPermalink }} → /that-page/
{{ with .OutputFormats.Get "json" }}
{{ .RelPermalink }} → /that-page/index.json
{{ end }}
```
In order for them to return the output format of the current template file instead, the given output format should have its `permalinkable` setting set to true.
**Same template file as above with json output format's `permalinkable` set to true:**
```go-html-template
{{ .RelPermalink }} → /that-page/index.json
{{ with .OutputFormats.Get "html" }}
{{ .RelPermalink }} → /that-page/
{{ end }}
```
From content files, you can use the [`ref` or `relref` shortcodes](/content-management/shortcodes/#ref-and-relref):
```go-html-template
[Neat]({{</* ref "blog/neat.md" "amp" */>}})
[Who]({{</* relref "about.md#who" "amp" */>}})
```
## Templates for your output formats
Each output format requires a corresponding template conforming to the [template lookup order](/templates/lookup-order/). Hugo considers both output format and suffix when selecting a template.
For example, to generate a JSON file for the home page, the template with highest specificity is `layouts/index.json.json`.
Hugo will now also detect the media type and output format of partials, if possible, and use that information to decide if the partial should be parsed as a plain text template or not.
Hugo will look for the name given, so you can name it whatever you want. But if you want it treated as plain text, you should use the file suffix and, if needed, the name of the Output Format. The pattern is as follows:
```go-html-template
[partial name].[OutputFormat].[suffix]
```
The partial below is a plain text template . The output format is `csv`, and since this is the only output format with the suffix `csv`, we don't need to include the output format `name`):
```go-html-template
{{ partial "mytextpartial.csv" . }}
```
[base]: /templates/base/
[site configuration]: /getting-started/configuration/
[lookup order]: /templates/lookup-order/
[media type]: https://en.wikipedia.org/wiki/Media_type
[partials]: /templates/partials/
[page_kinds]: /templates/section-templates/#page-kinds

View File

@@ -1,154 +0,0 @@
---
title: Pagination
description: Hugo supports pagination for your homepage, section pages, and taxonomies.
categories: [templates]
keywords: [lists,sections,pagination]
menu:
docs:
parent: templates
weight: 100
weight: 100
toc: true
aliases: [/extras/pagination,/doc/pagination/]
---
The real power of Hugo pagination shines when combined with the [`where`] function and its SQL-like operators: [`first`], [`last`], and [`after`]. You can even [order the content][lists] the way you've become used to with Hugo.
## Configure pagination
Pagination can be configured in your [site configuration][configuration]:
paginate
: default = `10`. This setting can be overridden within the template.
paginatePath
: default = `page`. Allows you to set a different path for your pagination pages.
Setting `paginate` to a positive value will split the list pages for the homepage, sections and taxonomies into chunks of that size. But note that the generation of the pagination pages for sections, taxonomies and homepage is *lazy* --- the pages will not be created if not referenced by a `.Paginator` (see below).
`paginatePath` is used to adapt the `URL` to the pages in the paginator (the default setting will produce URLs on the form `/page/1/`.
## List paginator pages
{{% note %}}
`.Paginator` is provided to help you build a pager menu. This feature is currently only supported on homepage and list pages (i.e., taxonomies and section lists).
{{% /note %}}
There are two ways to configure and use a `.Paginator`:
1. The simplest way is just to call `.Paginator.Pages` from a template. It will contain the pages for *that page*.
2. Select another set of pages with the available template functions and ordering options, and pass the slice to `.Paginate`, e.g.
* `{{ range (.Paginate ( first 50 .Pages.ByTitle )).Pages }}` or
* `{{ range (.Paginate .RegularPagesRecursive).Pages }}`.
For a given **Page**, it's one of the options above. The `.Paginator` is static and cannot change once created.
If you call `.Paginator` or `.Paginate` multiple times on the same page, you should ensure all the calls are identical. Once *either* `.Paginator` or `.Paginate` is called while generating a page, its result is cached, and any subsequent similar call will reuse the cached result. This means that any such calls which do not match the first one will not behave as written.
(Remember that function arguments are eagerly evaluated, so a call like `$paginator := cond x .Paginator (.Paginate .RegularPagesRecursive)` is an example of what you should *not* do. Use `if`/`else` instead to ensure exactly one evaluation.)
The global page size setting (`Paginate`) can be overridden by providing a positive integer as the last argument. The examples below will give five items per page:
* `{{ range (.Paginator 5).Pages }}`
* `{{ $paginator := .Paginate (where .Pages "Type" "posts") 5 }}`
It is also possible to use the `GroupBy` functions in combination with pagination:
```go-html-template
{{ range (.Paginate (.Pages.GroupByDate "2006")).PageGroups }}
```
## Build the navigation
The `.Paginator` contains enough information to build a paginator interface.
The easiest way to add this to your pages is to include the built-in template (with `Bootstrap`-compatible styles):
```go-html-template
{{ template "_internal/pagination.html" . }}
```
{{% note %}}
If you use any filters or ordering functions to create your `.Paginator` *and* you want the navigation buttons to be shown before the page listing, you must create the `.Paginator` before it's used.
{{% /note %}}
The following example shows how to create `.Paginator` before its used:
```go-html-template
{{ $paginator := .Paginate (where .Pages "Type" "posts") }}
{{ template "_internal/pagination.html" . }}
{{ range $paginator.Pages }}
{{ .Title }}
{{ end }}
```
Without the `where` filter, the above example is even simpler:
```go-html-template
{{ template "_internal/pagination.html" . }}
{{ range .Paginator.Pages }}
{{ .Title }}
{{ end }}
```
If you want to build custom navigation, you can do so using the `.Paginator` object, which includes the following properties:
PageNumber
: The current page's number in the pager sequence
URL
: The relative URL to the current pager
Pages
: The pages in the current pager
NumberOfElements
: The number of elements on this page
HasPrev
: Whether there are page(s) before the current
Prev
: The pager for the previous page
HasNext
: Whether there are page(s) after the current
Next
: The pager for the next page
First
: The pager for the first page
Last
: The pager for the last page
Pagers
: A list of pagers that can be used to build a pagination menu
PageSize
: Size of each pager
TotalPages
: The number of pages in the paginator
TotalNumberOfElements
: The number of elements on all pages in this paginator
## Additional information
The pages are built on the following form (`BLANK` means no value):
```txt
[SECTION/TAXONOMY/BLANK]/index.html
[SECTION/TAXONOMY/BLANK]/page/1/index.html => redirect to [SECTION/TAXONOMY/BLANK]/index.html
[SECTION/TAXONOMY/BLANK]/page/2/index.html
....
```
[`first`]: /functions/collections/first/
[`last`]: /functions/collections/last/
[`after`]: /functions/collections/after/
[configuration]: /getting-started/configuration/
[lists]: /templates/lists/
[`where`]: /functions/collections/where

View File

@@ -1,182 +0,0 @@
---
title: Partial templates
description: Partials are smaller, context-aware components in your list and page templates that can be used economically to keep your templating DRY.
categories: [templates]
keywords: [lists,sections,partials]
menu:
docs:
parent: templates
weight: 120
weight: 120
toc: true
aliases: [/templates/partial/,/layout/chrome/,/extras/analytics/]
---
{{< youtube pjS4pOLyB7c >}}
## Partial template lookup order
Partial templates---like [single page templates][singletemps] and [list page templates][listtemps]---have a specific [lookup order]. However, partials are simpler in that Hugo will only check in two places:
1. `layouts/partials/*<PARTIALNAME>.html`
2. `themes/<THEME>/layouts/partials/*<PARTIALNAME>.html`
This allows a theme's end user to copy a partial's contents into a file of the same name for [further customization][customize].
## Use partials in your templates
All partials for your Hugo project are located in a single `layouts/partials` directory. For better organization, you can create multiple subdirectories within `partials` as well:
```txt
layouts/
└── partials/
├── footer/
│ ├── scripts.html
│ └── site-footer.html
├── head/
│ ├── favicons.html
│ ├── metadata.html
│ ├── prerender.html
│ └── twitter.html
└── header/
├── site-header.html
└── site-nav.html
```
All partials are called within your templates using the following pattern:
```go-html-template
{{ partial "<PATH>/<PARTIAL>.html" . }}
```
{{% note %}}
One of the most common mistakes with new Hugo users is failing to pass a context to the partial call. In the pattern above, note how "the dot" (`.`) is required as the second argument to give the partial context. You can read more about "the dot" in the [Hugo templating introduction](/templates/introduction/).
{{% /note %}}
{{% note %}}
`<PARTIAL>` including `baseof` is reserved. ([#5373](https://github.com/gohugoio/hugo/issues/5373))
{{% /note %}}
As shown in the above example directory structure, you can nest your directories within `partials` for better source organization. You only need to call the nested partial's path relative to the `partials` directory:
```go-html-template
{{ partial "header/site-header.html" . }}
{{ partial "footer/scripts.html" . }}
```
### Variable scoping
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`.
## Returning a value from a partial
In addition to outputting markup, partials can be used to return a value of any type. In order to return a value, a partial must include a lone `return` statement *at the end of the partial*.
### Example GetFeatured
```go-html-template
{{/* layouts/partials/GetFeatured.html */}}
{{ return first . (where site.RegularPages "Params.featured" true) }}
```
```go-html-template
{{/* layouts/index.html */}}
{{ range partial "GetFeatured.html" 5 }}
[...]
{{ end }}
```
### Example GetImage
```go-html-template
{{/* layouts/partials/GetImage.html */}}
{{ $image := false }}
{{ with .Params.gallery }}
{{ $image = index . 0 }}
{{ end }}
{{ with .Params.image }}
{{ $image = . }}
{{ end }}
{{ return $image }}
```
```go-html-template
{{/* layouts/_default/single.html */}}
{{ with partial "GetImage.html" . }}
[...]
{{ end }}
```
{{% note %}}
Only one `return` statement is allowed per partial file.
{{% /note %}}
## Inline partials
You can also define partials inline in the template. But remember that template namespace is global, so you need to make sure that the names are unique to avoid conflicts.
```go-html-template
Value: {{ partial "my-inline-partial.html" . }}
{{ define "partials/my-inline-partial.html" }}
{{ $value := 32 }}
{{ return $value }}
{{ end }}
```
## Cached partials
The `partialCached` template function provides significant performance gains for complex templates that don't need to be re-rendered on every invocation. See&nbsp;[details][partialcached].
## Examples
### `header.html`
The following `header.html` partial template is used for [spf13.com](https://spf13.com/):
{{< code file=layouts/partials/header.html >}}
<!DOCTYPE html>
<html class="no-js" lang="en-US" prefix="og: http://ogp.me/ns# fb: http://ogp.me/ns/fb#">
<head>
<meta charset="utf-8">
{{ partial "meta.html" . }}
<base href="{{ .Site.BaseURL }}">
<title> {{ .Title }} : spf13.com </title>
<link rel="canonical" href="{{ .Permalink }}">
{{ if .RSSLink }}<link href="{{ .RSSLink }}" rel="alternate" type="application/rss+xml" title="{{ .Title }}" />{{ end }}
{{ partial "head_includes.html" . }}
</head>
{{< /code >}}
{{% note %}}
The `header.html` example partial was built before the introduction of block templates to Hugo. Read more on [base templates and blocks](/templates/base/) for defining the outer chrome or shell of your master templates (i.e., your site's head, header, and footer). You can even combine blocks and partials for added flexibility.
{{% /note %}}
### `footer.html`
The following `footer.html` partial template is used for [spf13.com](https://spf13.com/):
{{< code file=layouts/partials/footer.html >}}
<footer>
<div>
<p>
&copy; 2013-14 Steve Francia.
<a href="https://creativecommons.org/licenses/by/3.0/" title="Creative Commons Attribution">Some rights reserved</a>;
please attribute properly and link back.
</p>
</div>
</footer>
{{< /code >}}
[context]: /templates/introduction/
[customize]: /hugo-modules/theme-components/
[listtemps]: /templates/lists/
[lookup order]: /templates/lookup-order/
[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 | safeURL }}">{{ .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

@@ -1,59 +0,0 @@
---
title: Robots.txt file
linkTitle: Robots.txt
description: Hugo can generate a customized robots.txt in the same way as any other template.
categories: [templates]
keywords: [robots,search engines]
menu:
docs:
parent: templates
weight: 230
weight: 230
aliases: [/extras/robots-txt/]
---
To generate a robots.txt file from a template, change the [site configuration]:
{{< code-toggle file=hugo >}}
enableRobotsTXT = true
{{< /code-toggle >}}
By default, Hugo generates robots.txt using an [internal template][internal].
```text
User-agent: *
```
Search engines that honor the Robots Exclusion Protocol will interpret this as permission to crawl everything on the site.
## robots.txt template lookup order
You may overwrite the internal template with a custom template. Hugo selects the template using this lookup order:
1. `/layouts/robots.txt`
2. `/themes/<THEME>/layouts/robots.txt`
## robots.txt template example
{{< code file=layouts/robots.txt >}}
User-agent: *
{{ range .Pages }}
Disallow: {{ .RelPermalink }}
{{ end }}
{{< /code >}}
This template creates a robots.txt file with a `Disallow` directive for each page on the site. Search engines that honor the Robots Exclusion Protocol will not crawl any page on the site.
{{% note %}}
To create a robots.txt file without using a template:
1. Set `enableRobotsTXT` to `false` in the site configuration.
2. Create a robots.txt file in the `static` directory.
Remember that Hugo copies everything in the [static directory][static] to the root of `publishDir` (typically `public`) when you build your site.
[static]: /getting-started/directory-structure/
{{% /note %}}
[site configuration]: /getting-started/configuration/
[internal]: https://github.com/gohugoio/hugo/blob/master/tpl/tplimpl/embedded/templates/_default/robots.txt

View File

@@ -1,91 +0,0 @@
---
title: RSS templates
description: Use the built-in RSS template, or create your own.
categories: [templates]
keywords: [rss,xml,templates]
menu:
docs:
parent: templates
weight: 160
weight: 160
toc: true
---
## Configuration
By default, when you build your site, Hugo generates RSS feeds for home, section, taxonomy, and term pages. Control feed generation in your site configuration. For example, to generate feeds for home and section pages, but not for taxonomy and term pages:
{{< code-toggle file=hugo >}}
[outputs]
home = ['html', 'rss']
section = ['html', 'rss']
taxonomy = ['html']
term = ['html']
{{< /code-toggle >}}
To disable feed generation for all [page kinds]:
{{< code-toggle file=hugo >}}
disableKinds = ['rss']
{{< /code-toggle >}}
By default, the number of items in each feed is unlimited. Change this as needed in your site configuration:
{{< code-toggle file=hugo >}}
[services.rss]
limit = 42
{{< /code-toggle >}}
Set `limit` to `-1` to generate an unlimited number of items per feed.
The built-in RSS template will render the following values, if present, from your site configuration:
{{< code-toggle file=hugo >}}
copyright = '© 2023 ABC Widgets, Inc.'
[params.author]
name = 'John Doe'
email = 'jdoe@example.org'
{{< /code-toggle >}}
## Include feed reference
To include a feed reference in the `head` element of your rendered pages, place this within the `head` element of your templates:
```go-html-template
{{ with .OutputFormats.Get "rss" -}}
{{ printf `<link rel=%q type=%q href=%q title=%q>` .Rel .MediaType.Type .Permalink site.Title | safeHTML }}
{{ end }}
```
Hugo will render this to:
```html
<link rel="alternate" type="application/rss+xml" href="https://example.org/index.xml" title="ABC Widgets">
```
## 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].
For example, to use different templates for home, section, taxonomy, and term pages:
```text
layouts/
└── _default/
├── home.rss.xml
├── section.rss.xml
├── taxonomy.rss.xml
└── term.rss.xml
```
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`).
{{< datatable-filtered "output" "layouts" "OutputFormat == rss" "Example" "OutputFormat" "Suffix" "Template Lookup Order" >}}

View File

@@ -1,110 +0,0 @@
---
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.
categories: [templates]
keywords: [lists,sections,templates]
menu:
docs:
parent: templates
weight: 80
weight: 80
toc: true
aliases: [/templates/sections/]
---
## Add content and front matter to section templates
To effectively leverage section page templates, you should first understand Hugo's [content organization](/content-management/organization/) and, specifically, the purpose of `_index.md` for adding content and front matter to section and other list pages.
## Section template lookup order
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 >}}
{{ define "main" }}
<main>
{{ .Content }}
<ul class="contents">
{{ range .Paginator.Pages }}
<li>{{ .Title }}
<div>
{{ partial "summary.html" . }}
</div>
</li>
{{ end }}
</ul>
{{ partial "pagination.html" . }}
</main>
{{ end }}
{{< /code >}}
### Example: using `.Site.GetPage`
The `.Site.GetPage` example that follows assumes the following project directory structure:
```txt
.
└── content
├── blog
│ ├── _index.md # "title: My Hugo Blog" in the front matter
│ ├── post-1.md
│ ├── post-2.md
│ └── post-3.md
└── events #Note there is no _index.md file in "events"
├── event-1.md
└── event-2.md
```
`.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>
```
Since `blog` has a section index page with front matter at `content/blog/_index.md`, the above code will return the following result:
```html
<h1>My Hugo Blog</h1>
```
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>
```
Which then returns the following:
```html
<h1>Events</h1>
```
[contentorg]: /content-management/organization/
[getpage]: /methods/page/getpage
[lists]: /templates/lists/
[lookup]: /templates/lookup-order/
[`where`]: /functions/collections/where
[sections]: /content-management/sections/

View File

@@ -1,413 +0,0 @@
---
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.
categories: [templates]
keywords: [shortcodes,templates]
menu:
docs:
parent: templates
weight: 130
weight: 130
aliases: [/functions/get]
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/).)
{{% /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.
{{< 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 /*/%}}`.
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:
```go-html-template
{{</* boxes/square */>}}
```
Note the forward slash.
### Shortcode template lookup order
Shortcode templates have a simple [lookup order]:
1. `/layouts/shortcodes/<SHORTCODE>.html`
2. `/themes/<THEME>/layouts/shortcodes/<SHORTCODE>.html`
### Positional vs. named parameters
You can create shortcodes using the following types of parameters:
* Positional parameters
* Named parameters
* Positional *or* named parameters (i.e, "flexible")
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.
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.
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.
### Access parameters
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.
To access a parameter by name, use the `.Get` method followed by the named parameter 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:
```go-html-template
{{ .Get 0 }}
```
For the second position, you would just use:
```go-html-template
{{ .Get 1 }}
```
`with` is great when the output depends on a parameter 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
most helpful when the condition depends on either of the values, or both:
```go-html-template
{{ if or (.Get "title") (.Get "alt") }} alt="{{ with .Get "alt" }}{{ . }}{{ else }}{{ .Get "title" }}{{ end }}"{{ end }}
```
#### `.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:
```go-html-template
{{ if strings.ContainsNonSpace .Inner }}
Inner is not empty
{{ 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:
```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:
$.Params
: these are the parameters 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].
#### `.IsNamedParams`
The `.IsNamedParams` variable checks whether the shortcode declaration uses named parameters 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:
```go-html-template
{{</* image src="images/my-image.jpg" */>}}
```
You could then include the following as part of your shortcode templating:
```go-html-template
{{ if .IsNamedParams }}
<img src="{{ .Get "src" }}" alt="">
{{ else }}
<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.
{{% /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.
### 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.
## Custom shortcode examples
The following are examples of the different types of shortcodes you can create via shortcode template files in `/layouts/shortcodes`.
### Single-word example: `year`
Let's assume you would like to keep mentions of your copyright year current in your content files without having to continually review your Markdown. Your goal is to be able to call the shortcode as follows:
```go-html-template
{{</* year */>}}
```
{{< code file=layouts/shortcodes/year.html >}}
{{ now.Format "2006" }}
{{< /code >}}
### 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]:
```go-html-template
{{</* youtube 09jf3ow9jfw */>}}
```
Would load the template at `/layouts/shortcodes/youtube.html`:
{{< code file=layouts/shortcodes/youtube.html >}}
<div class="embed video-player">
<iframe class="youtube-player" type="text/html" width="640" height="385" src="https://www.youtube.com/embed/{{ index .Params 0 }}" allowfullscreen frameborder="0">
</iframe>
</div>
{{< /code >}}
{{< code file=youtube-embed.html >}}
<div class="embed video-player">
<iframe class="youtube-player" type="text/html"
width="640" height="385"
src="https://www.youtube.com/embed/09jf3ow9jfw"
allowfullscreen frameborder="0">
</iframe>
</div>
{{< /code >}}
### Single named example: `image`
Let's say you want to create your own `img` shortcode rather than use Hugo's built-in [`figure` shortcode][figure]. Your goal is to be able to call the shortcode as follows in your content files:
{{< code file=content-image.md >}}
{{</* img src="/media/spf13.jpg" title="Steve Francia" */>}}
{{< /code >}}
You have created the shortcode at `/layouts/shortcodes/img.html`, which loads the following shortcode template:
{{< code file=layouts/shortcodes/img.html >}}
<!-- image -->
<figure {{ with .Get "class" }}class="{{ . }}"{{ end }}>
{{ with .Get "link" }}<a href="{{ . }}">{{ end }}
<img src="{{ .Get "src" }}" {{ if or (.Get "alt") (.Get "caption") }}alt="{{ with .Get "alt" }}{{ . }}{{ else }}{{ .Get "caption" }}{{ end }}"{{ end }} />
{{ if .Get "link" }}</a>{{ end }}
{{ if or (or (.Get "title") (.Get "caption")) (.Get "attr") }}
<figcaption>{{ if isset .Params "title" }}
<h4>{{ .Get "title" }}</h4>{{ end }}
{{ if or (.Get "caption") (.Get "attr") }}<p>
{{ .Get "caption" }}
{{ with .Get "attrlink" }}<a href="{{ . }}"> {{ end }}
{{ .Get "attr" }}
{{ if .Get "attrlink" }}</a> {{ end }}
</p> {{ end }}
</figcaption>
{{ end }}
</figure>
<!-- image -->
{{< /code >}}
Would be rendered as:
{{< code file=img-output.html >}}
<figure>
<img src="/media/spf13.jpg" />
<figcaption>
<h4>Steve Francia</h4>
</figcaption>
</figure>
{{< /code >}}
### Single flexible example: `vimeo`
```go-html-template
{{</* vimeo 49718712 */>}}
{{</* vimeo id="49718712" class="flex-video" */>}}
```
Would load the template found at `/layouts/shortcodes/vimeo.html`:
{{< code file=layouts/shortcodes/vimeo.html >}}
{{ if .IsNamedParams }}
<div class="{{ if .Get "class" }}{{ .Get "class" }}{{ else }}vimeo-container{{ end }}">
<iframe src="https://player.vimeo.com/video/{{ .Get "id" }}" allowfullscreen></iframe>
</div>
{{ else }}
<div class="{{ if len .Params | eq 2 }}{{ .Get 1 }}{{ else }}vimeo-container{{ end }}">
<iframe src="https://player.vimeo.com/video/{{ .Get 0 }}" allowfullscreen></iframe>
</div>
{{ end }}
{{< /code >}}
Would be rendered as:
{{< code file=vimeo-iframes.html >}}
<div class="vimeo-container">
<iframe src="https://player.vimeo.com/video/49718712" allowfullscreen></iframe>
</div>
<div class="flex-video">
<iframe src="https://player.vimeo.com/video/49718712" allowfullscreen></iframe>
</div>
{{< /code >}}
### Paired example: `highlight`
The following is taken from `highlight`, which is a [built-in shortcode] that ships with Hugo.
{{< code file=highlight-example.md >}}
{{</* highlight html */>}}
<html>
<body> This HTML </body>
</html>
{{</* /highlight */>}}
{{< /code >}}
The template for the `highlight` shortcode uses the following code, which is already included in Hugo:
```go-html-template
{{ .Get 0 | highlight .Inner }}
```
The rendered output of the HTML example code block will be as follows:
{{< code file=syntax-highlighted.html >}}
<div class="highlight" style="background: #272822"><pre style="line-height: 125%"><span style="color: #f92672">&lt;html&gt;</span>
<span style="color: #f92672">&lt;body&gt;</span> This HTML <span style="color: #f92672">&lt;/body&gt;</span>
<span style="color: #f92672">&lt;/html&gt;</span>
</pre></div>
{{< /code >}}
### 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.
The following example is contrived but demonstrates the concept. Assume you have a `gallery` shortcode that expects one named `class` parameter:
{{< code file=layouts/shortcodes/gallery.html >}}
<div class="{{ .Get "class" }}">
{{ .Inner }}
</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`:
{{< code file=layouts/shortcodes/img.html >}}
{{- $src := .Get "src" -}}
{{- with .Parent -}}
<img src="{{ $src }}" class="{{ .Get "class" }}-image">
{{- else -}}
<img src="{{ $src }}">
{{- end -}}
{{< /code >}}
You can then call your shortcode in your content as follows:
```go-html-template
{{</* gallery class="content-gallery" */>}}
{{</* img src="/images/one.jpg" */>}}
{{</* img src="/images/two.jpg" */>}}
{{</* /gallery */>}}
{{</* img src="/images/three.jpg" */>}}
```
This will output the following HTML. Note how the first two `img` shortcodes inherit the `class` value of `content-gallery` set with the call to the parent `gallery`, whereas the third `img` only uses `src`:
```html
<div class="content-gallery">
<img src="/images/one.jpg" class="content-gallery-image">
<img src="/images/two.jpg" class="content-gallery-image">
</div>
<img src="/images/three.jpg">
```
## Error handling in shortcodes
Use the [errorf](/functions/fmt/errorf) template function and [`.Position`] shortcode method to get useful error messages in shortcodes:
```sh
{{ with .Get "name" }}
{{ else }}
{{ errorf "missing value for parameter 'name': %s" .Position }}
{{ end }}
```
When the above fails, you will see an `ERROR` log similar to the below:
```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"
```
## Inline shortcodes
You can also implement your shortcodes inline -- e.g. where you use them in the content file. This can be useful for scripting that you only need in one place.
This feature is disabled by default, but can be enabled in your site configuration:
{{< code-toggle file=hugo >}}
[security]
enableInlineShortcodes = true
{{< /code-toggle >}}
It is disabled by default for security reasons. The security model used by Hugo's template handling assumes that template authors are trusted, but that the content files are not, so the templates are injection-safe from malformed input data. But in most situations you have full control over the content, too, and then `enableInlineShortcodes = true` would be considered safe. But it's something to be aware of: It allows ad-hoc [Go Text templates](https://golang.org/pkg/text/template/) to be executed from the content files.
And once enabled, you can do this in your content files:
```go-html-template
{{</* time.inline */>}}{{ now }}{{</* /time.inline */>}}
```
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.
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:
```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
[vimeoexample]: #single-flexible-example-vimeo
[youtubeshortcode]: /content-management/shortcodes/#youtube

View File

@@ -1,85 +0,0 @@
---
title: Single page templates
description: The primary view of content in Hugo is the single view. Hugo will render every Markdown file provided with a corresponding single template.
categories: [templates]
keywords: [page, templates]
menu:
docs:
parent: templates
weight: 50
weight: 50
toc: true
aliases: [/layout/content/]
---
## Single page template lookup order
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">
<h1 id="title">{{ .Title }}</h1>
<div>
<article id="content">
{{ .Content }}
</article>
</div>
</section>
<aside id="meta">
<div>
<section>
<h4 id="date"> {{ .Date.Format "Mon Jan 2, 2006" }} </h4>
<h5 id="wordcount"> {{ .WordCount }} Words</h5>
</section>
{{ with .GetTerms "topics" }}
<ul id="topics">
{{ range . }}
<li><a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a></li>
{{ end }}
</ul>
{{ end }}
{{ with .GetTerms "tags" }}
<ul id="tags">
{{ range . }}
<li><a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a></li>
{{ end }}
</ul>
{{ end }}
</div>
<div>
{{ with .PrevInSection }}
<a class="previous" href="{{ .RelPermalink }}"> {{ .LinkTitle }}</a>
{{ end }}
{{ with .NextInSection }}
<a class="next" href="{{ .RelPermalink }}"> {{ .LinkTitle }}</a>
{{ end }}
</div>
</aside>
{{ end }}
{{< /code >}}
To easily generate new instances of a content type (e.g., new `.md` files in a section like `project/`) with preconfigured front matter, use [content archetypes][archetypes].
[archetypes]: /content-management/archetypes/
[base templates]: /templates/base/
[content type]: /content-management/types/
[directory structure]: /getting-started/directory-structure/
[dry]: https://en.wikipedia.org/wiki/Don%27t_repeat_yourself
[`.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

@@ -1,79 +0,0 @@
---
title: Sitemap templates
description: Hugo provides built-in sitemap templates.
categories: [templates]
keywords: [sitemap,xml,templates]
menu:
docs:
parent: templates
weight: 170
weight: 170
toc: true
aliases: [/layout/sitemap/,/templates/sitemap/]
---
## Overview
Hugo's built-in 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 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
## Configuration
Set the default values for [change frequency] and [priority], and the name of the generated file, in your site configuration.
{{< 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).
filename
: 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).
## Override default values
Override the default values for a given page in front matter.
{{< code-toggle file=news.md fm=true >}}
title = 'News'
[sitemap]
changefreq = 'weekly'
priority = 0.8
{{</ code-toggle >}}
## Override built-in templates
To override the built-in sitemap.xml template, create a new file in either of these locations:
- layouts/sitemap.xml
- layouts/_default/sitemap.xml
When ranging through the page collection, access the _change frequency_ and _priority_ with `.Sitemap.ChangeFreq` and `.Sitemap.Priority` respectively.
To override the built-in sitemapindex.xml template, create a new file in either of these locations:
- layouts/sitemapindex.xml
- layouts/_default/sitemapindex.xml
## Disable sitemap generation
You may disable sitemap generation in your site configuration:
{{< code-toggle file=hugo >}}
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

@@ -1,318 +0,0 @@
---
title: Taxonomy templates
description: Taxonomy templating includes taxonomy list pages, taxonomy terms pages, and using taxonomies in your single page templates.
categories: [templates]
keywords: [taxonomies,metadata,front matter,terms,templates]
menu:
docs:
parent: templates
weight: 90
weight: 90
toc: true
aliases: [/taxonomies/displaying/,/templates/terms/,/indexes/displaying/,/taxonomies/templates/,/indexes/ordering/, /templates/taxonomies/, /templates/taxonomy/]
---
Hugo includes support for user-defined groupings of content called **taxonomies**. Taxonomies are classifications that demonstrate logical relationships between content. See [Taxonomies under Content Management](/content-management/taxonomies) if you are unfamiliar with how Hugo leverages this powerful feature.
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)
* List a single content's taxonomy terms within a [single page template]
## Taxonomy list templates
Taxonomy list page templates are lists and therefore have all the variables and methods available to [list pages][lists].
### Taxonomy list template lookup order
See [Template Lookup](/templates/lookup-order/).
## Taxonomy terms templates
### Taxonomy terms templates lookup order
See [Template Lookup](/templates/lookup-order/).
### Taxonomy methods
A Taxonomy is a `map[string]WeightedPages`.
.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
Since Maps are unordered, an OrderedTaxonomy is a special structure that has a defined order.
```go
[]struct {
Name string
WeightedPages WeightedPages
}
```
Each element of the slice has:
.Term
: The Term used.
.WeightedPages
: A slice of Weighted Pages.
.Count
: The number of pieces of content assigned to this term.
.Page
: Returns a page reference for this term.
.Pages
: All Pages assigned to this term. All [list methods][renderlists] are available to this.
## WeightedPages
WeightedPages is simply a slice of WeightedPage.
```go
type WeightedPages []WeightedPage
```
.Count
: The number of pieces of content assigned to this term.
.Page
: Returns a page reference for this term.
.Pages
: Returns a slice of pages, which then can be ordered using any of the [list methods][renderlists].
## 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:
```go-html-template
<ul>
{{ range .Pages }}
<li>
<a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a>
{{ .Params.wikipedia }}
</li>
{{ end }}
</ul>
```
## Order taxonomies
Taxonomies can be ordered by either alphabetical key or by the number of content pieces assigned to that key.
### Order alphabetically example
```go-html-template
<ul>
{{ range .Data.Terms.Alphabetical }}
<li><a href="{{ .Page.Permalink }}">{{ .Page.Title }}</a> {{ .Count }}</li>
{{ end }}
</ul>
```
## Order content within taxonomies
Hugo uses both `date` and `weight` to order content within taxonomies.
Each piece of content in Hugo can optionally be assigned a date. It can also be assigned a weight for each taxonomy it is assigned to.
When iterating over content within taxonomies, the default sort is the same as that used for section and list pages: first by weight, then by date. This means that if the weights for two pieces of content are the same, then the more recent content will be displayed first.
The default weight for any piece of content is 0. Zero means "does not have a weight", not "has a weight of numerical value zero".
Weights of zero are thus treated specially: if two pages have unequal weights, and one of them is zero, then the zero-weighted page will always appear after the other one, regardless of the other's weight. Zero weights should thus be used with care: for example, if both positive and negative weights are used to extend a sequence in both directions, a zero-weighted page will appear not in the middle of the list, but at the end.
### Assign weight
Content can be assigned weight for each taxonomy that it's assigned to.
{{< code-toggle file=content/example.md fm=true >}}
tags = [ "a", "b", "c" ]
tags_weight = 22
categories = ["d"]
title = "Example"
categories_weight = 44
{{< /code-toggle >}}
The convention is `taxonomyname_weight`.
In the above example, this piece of content has a weight of 22 which applies to the sorting when rendering the pages assigned to the "a", "b" and "c" values of the 'tag' taxonomy.
It has also been assigned the weight of 44 when rendering the 'd' category.
With this the same piece of content can appear in different positions in different taxonomies.
Currently taxonomies only support the default ordering of content which is weight -> date.
There are two different templates that the use of taxonomies will require you to provide.
Both templates are covered in detail in the templates section.
A [list template](/templates/lists/) is any template that will be used to render multiple pieces of content in a single html page. This template will be used to generate all the automatically created taxonomy pages.
A [taxonomy template](/templates/taxonomy-templates/) is a template used to
generate the list of terms for a given template.
There are four common ways you can display the data in your
taxonomies in addition to the automatic taxonomy pages created by hugo
using the [list templates](/templates/lists/):
1. For a given piece of content, you can list the terms attached
2. For a given piece of content, you can list other content with the same
term
3. You can list all terms for a taxonomy
4. You can list all taxonomies (with their terms)
## List terms assigned to a page
List the terms assigned to a page using the `.Page.GetTerms` method.
To render an unordered list:
```go-html-template
{{ $taxonomy := "tags" }}
{{ with .GetTerms $taxonomy }}
<p>{{ (site.GetPage $taxonomy).LinkTitle }}:</p>
<ul>
{{ range . }}
<li><a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a></li>
{{ end }}
</ul>
{{ end }}
```
To render a comma-delimited list:
```go-html-template
{{ $taxonomy := "tags" }}
{{ with .GetTerms $taxonomy }}
<p>
{{ (site.GetPage $taxonomy).LinkTitle }}:
{{ range $k, $_ := . -}}
{{ if $k }}, {{ end }}
<a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a>
{{- end }}
</p>
{{ end }}
```
## 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:
### Example: showing content in same series
```go-html-template
<ul>
{{ range .Site.Taxonomies.series.golang }}
<li><a href="{{ .Page.RelPermalink }}">{{ .Page.Title }}</a></li>
{{ end }}
</ul>
```
## List all content in a given taxonomy
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>
<ul>
{{ range $taxonomy.Pages }}
<li><a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a></li>
{{ end }}
</ul>
{{ end }}
</ul>
</section>
```
## 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 }}
<li><a href="{{ .Page.Permalink }}">{{ .Page.Title }}</a> {{ .Count }}</li>
{{ 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 }}
<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>
{{< /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
[lists]: /templates/lists/
[renderlists]: /templates/lists/
[single page template]: /templates/single-page-templates/
[sitevars]: /variables/site/

View File

@@ -1,113 +0,0 @@
---
title: Content view templates
description: Hugo can render alternative views of your content, useful in list and summary views.
categories: [templates]
keywords: [views]
menu:
docs:
parent: templates
weight: 110
weight: 110
toc: true
---
These alternative **content views** are especially useful in [list templates][lists].
The following are common use cases for content views:
* You want content of every type to be shown on the homepage but only with limited [summary views][summaries].
* You only want a bulleted list of your content on a [taxonomy list page][taxonomylists]. Views make this very straightforward by delegating the rendering of each different type of content to the content itself.
## Create a content view
To create a new view, create a template in each of your different content type directories with the view name. The following example contains an "li" view and a "summary" view for the `posts` and `project` content types. As you can see, these sit next to the [single content view][single] template, `single.html`. You can even provide a specific view for a given type and continue to use the `_default/single.html` for the primary view.
```txt
▾ layouts/
▾ posts/
li.html
single.html
summary.html
▾ project/
li.html
single.html
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.
```txt
▾ layouts/
▾ _default/
li.html
single.html
summary.html
```
## Which template will be rendered?
The following is the [lookup order][lookup] for content views:
1. `/layouts/<TYPE>/<VIEW>.html`
2. `/layouts/_default/<VIEW>.html`
3. `/themes/<THEME>/layouts/<TYPE>/<VIEW>.html`
4. `/themes/<THEME>/layouts/_default/<VIEW>.html`
## Example: content view inside a list
The following example demonstrates how to use content views inside your [list templates][lists].
### `list.html`
In this example, `.Render` is passed into the template to call the [render function][render]. `.Render` is a special function that instructs content to render itself with the view template provided as the first argument. In this case, the template is going to render the `summary.html` view that follows:
{{< code file=layouts/_default/list.html >}}
<main id="main">
<div>
<h1 id="title">{{ .Title }}</h1>
{{ range .Pages }}
{{ .Render "summary" }}
{{ end }}
</div>
</main>
{{< /code >}}
### `summary.html`
Hugo will pass the entire page object to the following `summary.html` view template. (See [Page Variables][pagevars] for a complete list.)
{{< code file=layouts/_default/summary.html >}}
<article class="post">
<header>
<h2><a href="{{ .RelPermalink }}">{{ .Title }}</a></h2>
<div class="post-meta">{{ .Date.Format "Mon, Jan 2, 2006" }} - {{ .FuzzyWordCount }} Words </div>
</header>
{{ .Summary }}
<footer>
<a href='{{ .RelPermalink }}'>Read&nbsp;more&nbsp;&raquo;</a>
</footer>
</article>
{{< /code >}}
### `li.html`
Continuing on the previous example, we can change our render function to use a smaller `li.html` view by changing the argument in the call to the `.Render` function (i.e., `{{ .Render "li" }}`).
{{< code file=layouts/_default/li.html >}}
<li>
<a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a>
<div class="meta">{{ .Date.Format "Mon, Jan 2, 2006" }}</div>
</li>
{{< /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/