Merge commit '00c4484c7092181729f6f470805bc7d72e8ad17b'

This commit is contained in:
Bjørn Erik Pedersen
2022-11-17 16:16:19 +01:00
217 changed files with 2437 additions and 2821 deletions

View File

@@ -22,7 +22,7 @@ When using Hugo with [GitHub Pages](https://pages.github.com/), you can provide
In addition to the standard page variables, the 404 page has access to all site content accessible from `.Pages`.
```
```txt
▾ layouts/
404.html
```
@@ -52,7 +52,8 @@ Your 404.html file can be set to load automatically when a visitor enters a mist
* 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 website. You can specify the `Error document path` in the Static website configuration page of the Azure portal. [More details are available in the Static website documentation](https://docs.microsoft.com/en-us/azure/storage/blobs/storage-blob-static-website).
* 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.

View File

@@ -1,21 +0,0 @@
---
title: DEPRECATED - Alternative Templating Languages
linktitle: Alternative Templating
description: DEPRECATED - Support for Ace & Amber templating has been removed in version 0.62
date: 2017-02-01
publishdate: 2017-02-01
lastmod: 2017-02-20
categories: [templates]
keywords: [amber,ace,templating languages]
menu:
docs:
parent: "templates"
weight: 170
weight: 170
sections_weight: 170
draft: false
aliases: [/templates/ace/,/templates/amber/]
toc: true
---
Support for Amber and Ace templates has been removed since Hugo 0.62 per [issue #6609](https://github.com/gohugoio/hugo/issues/6609).

View File

@@ -4,7 +4,6 @@ linktitle:
description: The base and block constructs allow you to define the outer shell of your master templates (i.e., the chrome of the page).
date: 2017-02-01
publishdate: 2017-02-01
lastmod: 2017-02-01
categories: [templates,fundamentals]
keywords: [blocks,base]
menu:
@@ -24,7 +23,7 @@ The `block` keyword allows you to define the outer shell of your pages' one or m
## Base Template Lookup Order
{{< new-in "0.63.0" >}} Since Hugo v0.63, the base template lookup order closely follows that of the template it applies to (e.g. `_default/list.html`).
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.
@@ -75,7 +74,7 @@ This replaces the contents of our (basically empty) "main" block with something
{{% warning %}}
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

View File

@@ -4,7 +4,6 @@ linktitle:
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.
date: 2017-02-01
publishdate: 2017-02-01
lastmod: 2017-03-12
categories: [templates]
keywords: [data,dynamic,csv,json,toml,yaml,xml]
menu:
@@ -13,7 +12,6 @@ menu:
weight: 80
weight: 80
sections_weight: 80
draft: false
aliases: [/extras/datafiles/,/extras/datadrivencontent/,/doc/datafiles/]
toc: true
---
@@ -30,9 +28,23 @@ The `data` folder is where you can store additional data for Hugo to use when ge
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.
If you wish to access the data using the `.Site.Data.filename` notation, the filename must begin with an underscore or a Unicode letter, followed by zero or more underscores, Unicode letters, or Unicode digits. eg:
- `123.json` - Invalid
- `x123.json` - Valid
- `_123.json` - Valid
If you wish to access the data using the [`index`](/functions/index-function/) function, the filename 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 [Hugo themes][themes] but note that theme data files follow the same logic as other template files in the [Hugo lookup order][lookup] (i.e., given two files with the same name and relative path, the file in the root project `data` directory will override the file in the `themes/<THEME>/data` directory).
Data Files can also be used in [Hugo themes][themes] but note that theme data files are merged with the project directory taking precedence (i.e., 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 take care to not 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.
@@ -75,7 +87,7 @@ The list of bass players can be accessed via `.Site.Data.jazz.bass`, a single ba
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 }}
@@ -83,7 +95,7 @@ You can now render the list of recordings for all the bass players in a template
And then in the `partials/artist.html`:
```
```go-html-template
<ul>
{{ range .discography }}
<li>{{ . }}</li>
@@ -108,7 +120,7 @@ Achievements:
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>
```
@@ -119,14 +131,14 @@ Note the use of the [`markdownify` template function][markdownify]. This will se
Use `getJSON` or `getCSV` to get remote data:
```
```go-html-template
{{ $dataJ := getJSON "url" }}
{{ $dataC := getCSV "separator" "url" }}
```
If you use a prefix or postfix for the URL, the functions accept [variadic arguments][variadic]:
```
```go-html-template
{{ $dataJ := getJSON "url prefix" "arg1" "arg2" "arg n" }}
{{ $dataC := getCSV "separator" "url prefix" "arg1" "arg2" "arg n" }}
```
@@ -135,28 +147,28 @@ The separator for `getCSV` must be put in the first position and can only be one
All passed arguments will be joined to the final URL:
```
```go-html-template
{{ $urlPre := "https://api.github.com" }}
{{ $gistJ := getJSON $urlPre "/users/GITHUB_USERNAME/gists" }}
```
This will resolve internally to the following:
```
```go-html-template
{{ $gistJ := getJSON "https://api.github.com/users/GITHUB_USERNAME/gists" }}
```
### Add HTTP headers
{{< new-in "0.84.0" >}} Both `getJSON` and `getCSV` takes an optional map as the last argument, e.g.:
Both `getJSON` and `getCSV` takes an optional map as the last argument, e.g.:
```
```go-html-template
{{ $data := getJSON "https://example.org/api" (dict "Authorization" "Bearer abcd") }}
```
If you need multiple values for the same header key, use a slice:
```
```go-html-template
{{ $data := getJSON "https://example.org/api" (dict "X-List" (slice "a" "b" "c")) }}
```
@@ -197,7 +209,7 @@ With the command-line flag `--cacheDir`, you can specify any folder on your syst
You can also set `cacheDir` in the [main configuration file][config].
If you don't like caching at all, you can fully disable caching with the command line flag `--ignoreCache`.
If you don't like caching at all, you can fully disable caching with the command-line flag `--ignoreCache`.
### Authentication When Using REST URLs
@@ -210,7 +222,7 @@ To load local files with `getJSON` and `getCSV`, the source files must reside wi
It applies the same output logic as above in [Get Remote Data](#get-remote-data).
{{% note %}}
The local CSV files to be loaded using `getCSV` must be located **outside** of the `data` directory.
The local CSV files to be loaded using `getCSV` must be located **outside** the `data` directory.
{{% /note %}}
## LiveReload with Data Files

View File

@@ -37,15 +37,15 @@ The [`readfile` function][readFile] reads a file from disk and converts it into
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:
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" */>}}
```
@@ -53,8 +53,6 @@ As `readFile` is a function, it is only available to you in your templates and n
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.
{{% /warning %}}
[called directly in the Hugo docs]: https://github.com/gohugoio/hugoDocs/blob/master/content/en/templates/files.md
[dirindex]: https://github.com/gohugoio/hugo/blob/master/docs/layouts/shortcodes/directoryindex.html
[osfileinfo]: https://golang.org/pkg/os/#FileInfo

View File

@@ -27,38 +27,42 @@ While the following internal templates are called similar to partials, they do *
## Google Analytics
Hugo ships with internal templates for Google Analytics tracking, including both synchronous and asynchronous tracking codes. As well as support for both v3 and v4 of Google Analytics.
Hugo ships with internal templates supporting Google Analytics, both [Google Analytics 4][GA4] (GA4) and Universal Analytics.
**Note:** Universal Analytics are deprecated. For details, see [Universal Analytics will be going away][].
[GA4]: https://support.google.com/analytics/answer/10089681
[Universal Analytics will be going away]: https://support.google.com/analytics/answer/11583528
### Configure Google Analytics
Provide your tracking id in your configuration file:
Provide your tracking ID in your configuration file:
**Google Analytics v3 (analytics.js)**
{{< code-toggle file="config" >}}
googleAnalytics = "UA-PROPERTY_ID"
{{</ code-toggle >}}
**Google Analytics v4 (gtag.js)**
**Google Analytics 4 (gtag.js)**
{{< code-toggle file="config" >}}
googleAnalytics = "G-MEASUREMENT_ID"
{{</ code-toggle >}}
**Google Universal Analytics (analytics.js)**
{{< code-toggle file="config" >}}
googleAnalytics = "UA-PROPERTY_ID"
{{</ code-toggle >}}
### Use the Google Analytics Template
You can then include the Google Analytics internal template:
```
{{ template "_internal/google_analytics.html" . }}
```
```
```go-html-template
{{ template "_internal/google_analytics_async.html" . }}
```
When using Google Analytics v4 use `_internal/google_analytics.html`.
**Note:** The async template is _not_ suitable for Google Analytics 4.
A `.Site.GoogleAnalytics` variable is also exposed from the config.
```go-html-template
{{ template "_internal/google_analytics.html" . }}
```
If you want to create your own template, you can access the configured ID with `{{ site.Config.Services.GoogleAnalytics.ID }}`.
## Disqus
@@ -82,7 +86,7 @@ You also have the option to set the following in the front matter for a given pi
To add Disqus, include the following line in templates where you want your comments to appear:
```
```go-html-template
{{ template "_internal/disqus.html" . }}
```
@@ -118,11 +122,12 @@ The `if` statement skips the initialization of the Disqus comment injection when
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.
@@ -167,7 +172,7 @@ If using YouTube this will produce a og:video tag like `<meta property="og:video
To add Open Graph metadata, include the following line between the `<head>` tags in your templates:
```
```go-html-template
{{ template "_internal/opengraph.html" . }}
```
@@ -198,16 +203,31 @@ If no images are found at all, then an image-less Twitter `summary` card is used
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.
The `.Site.Social.twitter` variable is exposed from the config as the value for `twitter:site`.
{{< code-toggle file="config" >}}
[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 between the `<head>` tags in your templates:
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/google_analytics_async.html`

View File

@@ -4,7 +4,7 @@ linktitle: Templating
description: Hugo uses Go's `html/template` and `text/template` libraries as the basis for the templating.
date: 2017-02-01
publishdate: 2017-02-01
lastmod: 2017-02-25
lastmod: 2022-09-20
categories: [templates,fundamentals]
keywords: [go]
menu:
@@ -43,7 +43,7 @@ current scope (like the `.Title` example in the [Variables]({{< relref
Parameters for functions are separated using spaces. The general syntax is:
```
```go-html-template
{{ FUNCTION ARG1 ARG2 .. }}
```
@@ -70,8 +70,8 @@ Accessing the Page Parameter `bar` defined in a piece of content's [front matter
#### A Single Statement Can be Split over Multiple Lines
```go-html-template
{{ if or
(isset .Params "alt")
{{ if or
(isset .Params "alt")
(isset .Params "caption")
}}
```
@@ -107,6 +107,7 @@ The custom variables need to be prefixed with `$`.
{{ $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:
@@ -139,7 +140,7 @@ Go Templates only ship with a few basic functions but also provide a mechanism f
<!-- prints true (i.e., since 1 is less than 2) -->
```
Note that both examples make use of Go Template's [math]][] functions.
Note that both examples make use of Go Template's [math][math] functions.
{{% note "Additional Boolean Operators" %}}
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).
@@ -159,7 +160,7 @@ within Hugo.
### Partial
The [`partial`][partials] function is used to include *partial* templates using
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:
@@ -170,9 +171,9 @@ Example of including a `layouts/partials/header.html` partial:
### Template
The `template` function was used to include *partial* templates
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_ templates][internal templates]. The syntax is `{{ template
"_internal/<TEMPLATE>.<EXTENSION>" . }}`.
{{% note %}}
@@ -234,7 +235,7 @@ key.
{{ end }}
```
#### Example 5: Conditional on empty _map_, _array_, or _slice_.
#### 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.
@@ -293,7 +294,7 @@ 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 rebinded.
`if`. Here, the `.` does not get rebound.
Below example is "Example 1" rewritten using `if`:
@@ -382,22 +383,6 @@ Stuff Here
{{ end }}
```
### Example 4: Internet Explorer Conditional Comments {#ie-conditional-comments}
By default, Go Templates remove HTML comments from output. This has the unfortunate side effect of removing Internet Explorer conditional comments. As a workaround, use something like this:
```go-html-template
{{ "<!--[if lt IE 9]>" | safeHTML }}
<script src="html5shiv.js"></script>
{{ "<![endif]-->" | safeHTML }}
```
Alternatively, you can use the backtick (`` ` ``) to quote the IE conditional comments, avoiding the tedious task of escaping every double quotes (`"`) inside, as demonstrated in the [examples](https://golang.org/pkg/text/template/#hdr-Examples) in the Go text/template documentation:
```go-html-template
{{ `<!--[if lt IE 7]><html class="no-js lt-ie9 lt-ie8 lt-ie7"><![endif]-->` | safeHTML }}
```
## Context (aka "the dot") {#the-dot}
The most easily overlooked concept to understand about Go Templates is
@@ -405,7 +390,7 @@ 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 of an iteration, however, it will have the value of the
- 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.
@@ -430,7 +415,7 @@ The following shows how to define a variable independent of the context.
{{< /code >}}
{{% note %}}
Notice how once we have entered the loop (i.e. `range`), the value of `{{ . }}` has changed. We have defined a variable outside of the loop (`{{$title}}`) that we've assigned a value so that we have access to the value from within the loop as well.
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
@@ -511,7 +496,7 @@ Will render `Bonsoir, Eliott.`, and not care about the syntax error (`add 0 + 2`
### HTML comments
If you need to produce HTML comments from your templates, take a look at the [Internet Explorer conditional comments](#ie-conditional-comments) example. If you need variables to construct such HTML comments, just pipe `printf` to `safeHTML`. For example:
If you need to produce HTML comments from your templates, take a look at the [Internet Explorer conditional comments]({{< relref "introduction.md#ie-conditional-comments" >}}) example. 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 }}
@@ -544,7 +529,7 @@ An example of this is used in the Hugo docs. Most of the pages benefit from havi
Here is the example front matter (YAML):
```
```yml
---
title: Roadmap
lastmod: 2017-03-05

View File

@@ -59,7 +59,7 @@ It is important to note that all `_index.md` content files will render according
The following is an example of a typical Hugo project directory's content:
```
```txt
.
...
├── content
@@ -524,27 +524,27 @@ While these are logical defaults, they are not always the desired order. There a
#### 1. Adding the Reverse Method
```
```go-html-template
{{ range (.Pages.GroupBy "Section").Reverse }}
```
```
```go-html-template
{{ range (.Pages.GroupByDate "2006-01").Reverse }}
```
#### 2. Providing the Alternate Direction
```
```go-html-template
{{ range .Pages.GroupByDate "2006-01" "asc" }}
```
```
```go-html-template
{{ range .Pages.GroupBy "Section" "desc" }}
```
### Order Within Groups
Because Grouping returns a `{{.Key}}` and a slice of pages, all of the ordering methods listed above are available.
Because Grouping returns a `{{.Key}}` and a slice of pages, all the ordering methods listed above are available.
Here is the ordering for the example that follows:

View File

@@ -39,7 +39,7 @@ Language
: We will consider a language code 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".
: 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.

View File

@@ -20,8 +20,8 @@ toc: false
---
Hugo makes no assumptions about how your rendered HTML will be
structured. Instead, it provides all of the functions you will need to be
able to build your menu however you want.
structured. Instead, it provides all the functions you will need to
build your menu however you want.
The following is an example:
@@ -72,17 +72,17 @@ Use the [`absLangURL`](/functions/abslangurl) or [`relLangURL`](/functions/rella
To enable this menu, configure `sectionPagesMenu` in your site `config`:
```
```yml
sectionPagesMenu = "main"
```
The menu name can be anything, but take a note of what it is.
The menu name can be anything, but take a note of what it is.
This will create a menu with all the sections as menu items and all the sections' pages as "shadow-members". Ensure that all first level directories that you would like to show up on this menu are [Branch Bundles](https://gohugo.io/content-management/sections/). Leaf Bundles do not form sections.
The _shadow_ implies that the pages isn't represented by a menu-item themselves, but this enables you to create a top-level menu like this:
```
```go-html-template
<nav class="sidebar-nav">
{{ $currentPage := . }}
{{ range .Site.Menus.main }}
@@ -93,7 +93,6 @@ The _shadow_ implies that the pages isn't represented by a menu-item themselves,
In the above, the menu item is marked as active if on the current section's list page or on a page in that section.
## Site Config menus
The above is all that's needed. But if you want custom menu items, e.g. changing weight, name, or link title attribute, you can define them manually in the site config file:
@@ -117,7 +116,7 @@ It's also possible to create menu entries from the page (i.e. the `.md`-file).
Here is a `yaml` example:
```
```yml
---
title: Menu Templates
linktitle: Menu Templates
@@ -148,7 +147,7 @@ That's why you have to use the go template's `with` keyword or something similar
Here's an example:
```
```go-html-template
<nav class="sidebar-nav">
{{ range .Site.Menus.main }}
<a href="{{ .URL }}" title="{{ .Title }}">
@@ -169,7 +168,7 @@ User-defined content on menu items are accessible via `.Params`.
Here's an example:
```
```go-html-template
<nav class="sidebar-nav">
{{ range .Site.Menus.main }}
<a href="{{ .URL }}" title="{{ .Title }}" class="{{ with .Params.class }}{{ . }}{{ end }}">

View File

@@ -1,344 +0,0 @@
---
title: Ordering and Grouping Hugo Lists
linktitle: List Ordering and Grouping
description: You can group or order your content in both your templating and content front matter.
date: 2017-02-01
publishdate: 2017-02-01
lastmod: 2017-02-01
categories: [templates]
keywords: []
menu:
docs:
parent: "templates"
weight: 27
weight: 27
sections_weight: 27
draft: true
aliases: [/templates/ordering/,/templates/grouping/]
toc: true
notes: This was originally going to be a separate page on the new docs site but it now makes more sense to keep everything within the templates/lists page. - rdwatters, 2017-03-12.
---
In Hugo, a list template is any template that will be used to render multiple pieces of content in a single HTML page.
## Example List Templates
### Section Template
This list template is used for [spf13.com](https://spf13.com/). It makes use of [partial templates][partials]. All examples use a [view](/templates/views/) called either "li" or "summary."
{{< code file="layouts/section/post.html" >}}
{{ partial "header.html" . }}
{{ partial "subheader.html" . }}
<section id="main">
<div>
<h1 id="title">{{ .Title }}</h1>
<ul id="list">
{{ range .Pages }}
{{ .Render "li"}}
{{ end }}
</ul>
</div>
</section>
{{ partial "footer.html" . }}
{{< /code >}}
### Taxonomy Template
{{< code file="layouts/_default/taxonomies.html" download="taxonomies.html" >}}
{{ define "main" }}
<section id="main">
<div>
<h1 id="title">{{ .Title }}</h1>
{{ range .Pages }}
{{ .Render "summary"}}
{{ end }}
</div>
</section>
{{ end }}
{{< /code >}}
## Order Content
Hugo lists render the content based on metadata provided in the [front matter](/content-management/front-matter/)..
Here are a variety of different ways you can order the content items in
your list templates:
### Default: Weight > Date
{{< code file="layouts/partials/order-default.html" >}}
<ul class="pages">
{{ range .Pages }}
<li>
<h1><a href="{{ .Permalink }}">{{ .Title }}</a></h1>
<time>{{ .Date.Format "Mon, Jan 2, 2006" }}</time>
</li>
{{ end }}
</ul>
{{< /code >}}
### By Weight
{{< code file="layouts/partials/by-weight.html" >}}
{{ range .Pages.ByWeight }}
<li>
<a href="{{ .Permalink }}">{{ .Title }}</a>
<div class="meta">{{ .Date.Format "Mon, Jan 2, 2006" }}</div>
</li>
{{ end }}
{{< /code >}}
### By Date
{{< code file="layouts/partials/by-date.html" >}}
{{ range .Pages.ByDate }}
<li>
<a href="{{ .Permalink }}">{{ .Title }}</a>
<div class="meta">{{ .Date.Format "Mon, Jan 2, 2006" }}</div>
</li>
{{ end }}
{{< /code >}}
### By Publish Date
{{< code file="layouts/partials/by-publish-date.html" >}}
{{ range .Pages.ByPublishDate }}
<li>
<a href="{{ .Permalink }}">{{ .Title }}</a>
<div class="meta">{{ .PublishDate.Format "Mon, Jan 2, 2006" }}</div>
</li>
{{ end }}
{{< /code >}}
### By Expiration Date
{{< code file="layouts/partials/by-expiry-date.html" >}}
{{ range .Pages.ByExpiryDate }}
<li>
<a href="{{ .Permalink }}">{{ .Title }}</a>
<div class="meta">{{ .ExpiryDate.Format "Mon, Jan 2, 2006" }}</div>
</li>
{{ end }}
{{< /code >}}
### By Last Modified Date
{{< code file="layouts/partials/by-last-mod.html" >}}
{{ range .Pages.ByLastmod }}
<li>
<a href="{{ .Permalink }}">{{ .Title }}</a>
<div class="meta">{{ .Date.Format "Mon, Jan 2, 2006" }}</div>
</li>
{{ end }}
{{< /code >}}
### By Length
{{< code file="layouts/partials/by-length.html" >}}
{{ range .Pages.ByLength }}
<li>
<a href="{{ .Permalink }}">{{ .Title }}</a>
<div class="meta">{{ .Date.Format "Mon, Jan 2, 2006" }}</div>
</li>
{{ end }}
{{< /code >}}
### By Title
{{< code file="layouts/partials/by-title.html" >}}
{{ range .Pages.ByTitle }}
<li>
<a href="{{ .Permalink }}">{{ .Title }}</a>
<div class="meta">{{ .Date.Format "Mon, Jan 2, 2006" }}</div>
</li>
{{ end }}
{{< /code >}}
### By Link Title
{{< code file="layouts/partials/by-link-title.html" >}}
{{ range .Pages.ByLinkTitle }}
<li>
<a href="{{ .Permalink }}">{{ .LinkTitle }}</a>
<div class="meta">{{ .Date.Format "Mon, Jan 2, 2006" }}</div>
</li>
{{ end }}
{{< /code >}}
### By Parameter
Order based on the specified front matter parameter. Content that does not have the specified front matter field will use the site's `.Site.Params` default. If the parameter is not found at all in some entries, those entries will appear together at the end of the ordering.
The below example sorts a list of posts by their rating.
{{< code file="layouts/partials/by-rating.html" >}}
{{ range (.Pages.ByParam "rating") }}
<!-- ... -->
{{ end }}
{{< /code >}}
If the front matter field of interest is nested beneath another field, you can
also get it:
{{< code file="layouts/partials/by-nested-param.html" >}}
{{ range (.Pages.ByParam "author.last_name") }}
<!-- ... -->
{{ end }}
{{< /code >}}
### Reverse Order
Reversing order can be applied to any of the above methods. The following uses `ByDate` as an example:
{{< code file="layouts/partials/by-date-reverse.html" >}}
{{ range .Pages.ByDate.Reverse }}
<li>
<a href="{{ .Permalink }}">{{ .Title }}</a>
<div class="meta">{{ .Date.Format "Mon, Jan 2, 2006" }}</div>
</li>
{{ end }}
{{< /code >}}
## Group Content
Hugo provides some functions for grouping pages by Section, Type, Date, etc.
### By Page Field
{{< code file="layouts/partials/by-page-field.html" >}}
{{ range .Pages.GroupBy "Section" }}
<h3>{{ .Key }}</h3>
<ul>
{{ range .Pages }}
<li>
<a href="{{ .Permalink }}">{{ .Title }}</a>
<div class="meta">{{ .Date.Format "Mon, Jan 2, 2006" }}</div>
</li>
{{ end }}
</ul>
{{ end }}
{{< /code >}}
### By Page date
{{< code file="layouts/partials/by-page-date.html" >}}
{{ range .Pages.GroupByDate "2006-01" }}
<h3>{{ .Key }}</h3>
<ul>
{{ range .Pages }}
<li>
<a href="{{ .Permalink }}">{{ .Title }}</a>
<div class="meta">{{ .Date.Format "Mon, Jan 2, 2006" }}</div>
</li>
{{ end }}
</ul>
{{ end }}
{{< /code >}}
### By Page publish date
{{< code file="layouts/partials/by-page-publish-date.html" >}}
{{ range .Pages.GroupByPublishDate "2006-01" }}
<h3>{{ .Key }}</h3>
<ul>
{{ range .Pages }}
<li>
<a href="{{ .Permalink }}">{{ .Title }}</a>
<div class="meta">{{ .PublishDate.Format "Mon, Jan 2, 2006" }}</div>
</li>
{{ end }}
</ul>
{{ end }}
{{< /code >}}
### By Page Param
{{< code file="layouts/partials/by-page-param.html" >}}
{{ range .Pages.GroupByParam "param_key" }}
<h3>{{ .Key }}</h3>
<ul>
{{ range .Pages }}
<li>
<a href="{{ .Permalink }}">{{ .Title }}</a>
<div class="meta">{{ .Date.Format "Mon, Jan 2, 2006" }}</div>
</li>
{{ end }}
</ul>
{{ end }}
{{< /code >}}
### By Page Param in Date Format
{{< code file="layouts/partials/by-page-param-as-date.html" >}}
{{ range .Pages.GroupByParamDate "param_key" "2006-01" }}
<h3>{{ .Key }}</h3>
<ul>
{{ range .Pages }}
<li>
<a href="{{ .Permalink }}">{{ .Title }}</a>
<div class="meta">{{ .Date.Format "Mon, Jan 2, 2006" }}</div>
</li>
{{ end }}
</ul>
{{ end }}
{{< /code >}}
### Reverse Key Order
The ordering of the groups is performed by keys in alphanumeric order (AZ, 1100) and in reverse chronological order (newest first) for dates.
While these are logical defaults, they are not always the desired order. There are two different syntaxes to change the order, both of which work the same way. You can use your preferred syntax.
#### Reverse Method
```
{{ range (.Pages.GroupBy "Section").Reverse }}
```
```
{{ range (.Pages.GroupByDate "2006-01").Reverse }}
```
#### Provide the Alternate Direction
```
{{ range .Pages.GroupByDate "2006-01" "asc" }}
```
```
{{ range .Pages.GroupBy "Section" "desc" }}
```
### Order Within Groups
Because Grouping returns a `{{.Key}}` and a slice of pages, all of the ordering methods listed above are available.
In the following example, groups are ordered chronologically and then content
within each group is ordered alphabetically by title.
{{< code file="layouts/partials/by-group-by-page.html" >}}
{{ range .Pages.GroupByDate "2006-01" "asc" }}
<h3>{{ .Key }}</h3>
<ul>
{{ range .Pages.ByTitle }}
<li>
<a href="{{ .Permalink }}">{{ .Title }}</a>
<div class="meta">{{ .Date.Format "Mon, Jan 2, 2006" }}</div>
</li>
{{ end }}
</ul>
{{ end }}
{{< /code >}}
## Filter and Limiting Lists
See the [_Lists/Filtering and Limiting Lists_
section][filteringandlimitinglists] for details.
[views]: /templates/views/
[filteringandlimitinglists]: /templates/lists/#filtering-and-limiting-lists

View File

@@ -6,7 +6,7 @@ date: 2017-03-22
publishdate: 2017-03-22
lastmod: 2019-12-11
categories: [templates]
keywords: ["amp","outputs","rss"]
keywords: ["amp", "outputs", "rss"]
menu:
docs:
parent: "templates"
@@ -22,7 +22,7 @@ This page describes how to properly configure your site with the media types and
## Media Types
A [media type][] (also known as *MIME type* and *content type*) is a two-part identifier for file formats and format contents transmitted on the Internet.
A [media type][] (also known as _MIME type_ and _content 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:
@@ -30,10 +30,10 @@ This is the full set of built-in media types in Hugo:
**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 filenames 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.
- 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 filenames 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][config], either for all sites or for a given language.
@@ -70,9 +70,9 @@ This is the full set of Hugo's built-in output formats:
{{< datatable "output" "formats" "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 the `Type` of an already 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.
- 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 the `Type` of an already 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.
@@ -118,7 +118,7 @@ The following is the full list of configuration options for output formats and t
: 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`.
: 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`.
@@ -128,18 +128,19 @@ The following is the full list of configuration options for output formats and t
## Output Formats for Pages
A `Page` in Hugo can be rendered to multiple *output formats* on the file
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.
| Kind | Default Output Formats |
|--------------- |----------------------- |
| `page` | HTML |
| `home` | HTML, RSS |
| `section` | HTML, RSS |
| Kind | Default Output Formats |
| ---------- | ---------------------- |
| `page` | HTML |
| `home` | HTML, RSS |
| `section` | HTML, RSS |
| `taxonomy` | HTML, RSS |
| `term` | HTML, RSS |
@@ -157,12 +158,8 @@ Example from site config file:
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"]`.
{{< new-in "0.73.0" >}} We have fixed the before confusing page kinds used for taxonomies (see the listing below) to be in line with the terms used when we talk about taxonomies. We have been careful to avoid site breakage, and you should get an ERROR in the console if you need to adjust your `outputs` section.
Note that in the above examples, the _output formats_ for `section`,
`taxonomy` and `term` will stay at their default value `["HTML", "RSS"]`.
{{% page-kinds %}}
@@ -183,7 +180,7 @@ outputs:
---
```
## List Output formats
## 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>`:
@@ -207,7 +204,7 @@ __from `single.json.json`:__
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:__
**Same template file as above with json output format's `permalinkable` set to true:**
```go-html-template
{{ .RelPermalink }} > /that-page/index.json
@@ -231,7 +228,7 @@ A new output format needs a corresponding template in order to render anything u
The key distinction for Hugo versions 0.20 and newer is that Hugo looks at an output format's `Name` and MediaType's `Suffixes` when choosing the template used to render a given `Page`.
{{% /note %}}
The following table shows examples of different output formats, the suffix used, and Hugo's respective template [lookup order][]. All of the examples in the table can:
The following table shows examples of different output formats, the suffix used, and Hugo's respective template [lookup order][]. All the examples in the table can:
* Use a [base template][base].
* Include [partial templates][partials]
@@ -242,13 +239,13 @@ Hugo will now also detect the media type and output format of partials, if possi
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 (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's `Name`):
```
```go-html-template
{{ partial "mytextpartial.csv" . }}
```

View File

@@ -4,7 +4,6 @@ linktitle: Pagination
description: Hugo supports pagination for your homepage, section pages, and taxonomies.
date: 2017-02-01
publishdate: 2017-02-01
lastmod: 2017-02-01
categories: [templates]
keywords: [lists,sections,pagination]
menu:
@@ -13,7 +12,6 @@ menu:
weight: 140
weight: 140
sections_weight: 140
draft: false
aliases: [/extras/pagination,/doc/pagination/]
toc: true
---
@@ -60,7 +58,7 @@ The global page size setting (`Paginate`) can be overridden by providing a posit
It is also possible to use the `GroupBy` functions in combination with pagination:
```
```go-html-template
{{ range (.Paginate (.Pages.GroupByDate "2006")).PageGroups }}
```
@@ -70,7 +68,7 @@ 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" . }}
```
@@ -80,7 +78,7 @@ If you use any filters or ordering functions to create your `.Paginator` *and* y
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 }}
@@ -90,7 +88,7 @@ The following example shows how to create `.Paginator` before its used:
Without the `where` filter, the above example is even simpler:
```
```go-html-template
{{ template "_internal/pagination.html" . }}
{{ range .Paginator.Pages }}
{{ .Title }}
@@ -145,14 +143,13 @@ If you want to build custom navigation, you can do so using the `.Paginator` obj
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/first/
[`last`]: /functions/last/
[`after`]: /functions/after/

View File

@@ -78,7 +78,7 @@ This means the partial will *only* be able to access those variables. The partia
## 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_.
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
@@ -121,8 +121,6 @@ Only one `return` statement is allowed per partial file.
## Inline Partials
{{< new-in "0.74.0" >}}
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

View File

@@ -13,31 +13,31 @@ menu:
weight: 20
---
{{< new-in "0.62.0" >}} Note that this is only supported with the [Goldmark](/getting-started/configuration-markup#goldmark) renderer.
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`.{{< new-in "0.71.0" >}}
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` {{< new-in "0.71.0" >}}
* `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:
```goat { class="black f7" }
layouts
└── _default
└── _markup
```text
layouts/
└── _default/
└── _markup/
├── render-codeblock-bash.html
├── render-codeblock.html
├── render-heading.html
├── render-image.html
├── render-image.rss.xml
└── render-link.html
└── render-codeblock.html
└── render-codeblock-bash.html
```
Some use cases for the above:
@@ -83,10 +83,10 @@ Text
PlainText
: The plain variant of the above.
Attributes (map) {{< new-in "0.82.0" >}}
Attributes (map)
: A map of attributes (e.g. `id`, `class`)
### Link with title Markdown example:
### Link with title Markdown example
```md
[Text](https://www.gohugo.io "Title")
@@ -98,10 +98,10 @@ Here is a code example for how the render-link.html template could look:
<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:
### Image Markdown example
```md
![Text](https://d33wubrfki0l68.cloudfront.net/c38c7334cc3f23585738e40334284fddcaf03d5e/2e17c/images/hugo-logo-wide.svg "Title")
![Text](https://gohugo.io/images/hugo-logo-wide.svg "Title")
```
Here is a code example for how the render-image.html template could look:
@@ -146,7 +146,7 @@ layouts
└── render-codeblock-bash.html
```
The default behaviour 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 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:

View File

@@ -57,7 +57,7 @@ copyright = "This work is licensed under a Creative Commons Attribution-ShareAli
This is the default RSS template that ships with Hugo:
https://github.com/gohugoio/hugo/blob/master/tpl/tplimpl/embedded/templates/_default/rss.xml
<https://github.com/gohugoio/hugo/blob/master/tpl/tplimpl/embedded/templates/_default/rss.xml>
## Reference your RSS Feed in `<head>`

View File

@@ -70,7 +70,7 @@ Examples:
The `.Site.GetPage` example that follows assumes the following project directory structure:
```
```txt
.
└── content
├── blog
@@ -85,29 +85,28 @@ The `.Site.GetPage` example that follows assumes the following project directory
`.Site.GetPage` will return `nil` if no `_index.md` page is found. Therefore, if `content/blog/_index.md` does not exist, the template will output the section name:
```
```go-html-template
<h1>{{ with .Site.GetPage "section" "blog" }}{{ .Title }}{{ end }}</h1>
```
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]: /functions/getpage/
[lists]: /templates/lists/

View File

@@ -18,7 +18,7 @@ aliases: []
toc: true
---
Shortcodes are a means to consolidate templating into small, reusable snippets that you can embed directly inside of your content. In this sense, you can think of shortcodes as the intermediary between [page and list templates][templates] and [basic content files][].
Shortcodes are a means to consolidate templating into small, reusable snippets that you can embed directly inside your content. In this sense, you can think of shortcodes as the intermediary between [page and list templates][templates] and [basic content files][].
{{% note %}}
Hugo also ships with built-in shortcodes for common use cases. (See [Content Management: Shortcodes](/content-management/shortcodes/).)
@@ -36,7 +36,7 @@ To create a shortcode, place an HTML template in the `layouts/shortcodes` direct
You can organize your shortcodes in subfolders, e.g. in `layouts/shortcodes/boxes`. These shortcodes would then be accessible with their relative path, e.g:
```
```go-html-template
{{</* boxes/square */>}}
```
@@ -69,47 +69,50 @@ All shortcode parameters can be accessed via the `.Get` method. Whether you pass
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:
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 all of the content between the opening and closing shortcodes. If a closing shortcode is required, you can check the length of `.Inner` as an indicator of its existence.
If a closing shortcode is used, the `.Inner` variable will be populated with the content between the opening and closing shortcodes. If a closing shortcode is required, you can check the length of `.Inner` as an indicator of its existence.
A shortcode with content declared via the `.Inner` variable can also be declared without the
content and without the closing
by using the self-closing syntax:
A shortcode with content declared via the `.Inner` variable can also be declared without the content and without the closing by using the self-closing syntax:
```
```go-html-template
{{</* innershortcode /*/>}}
```
{{% warning %}}
Any shortcode that refers to `.Inner` must be closed or self-closed.
{{% /warning %}}
#### `.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:
@@ -129,13 +132,13 @@ The `.IsNamedParams` variable checks whether the shortcode declaration uses name
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 }}
@@ -163,9 +166,9 @@ The following are examples of the different types of shortcodes you can create v
### 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:
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 */>}}
```
@@ -175,9 +178,9 @@ Let's assume you would like to keep mentions of your copyright year current in y
### Single Positional Example: `youtube`
Embedded videos are a common addition to markdown content that can quickly become unsightly. The following is the code used by [Hugo's built-in YouTube shortcode][youtubeshortcode]:
Embedded videos are a common addition to Markdown content that can quickly become unsightly. The following is the code used by [Hugo's built-in YouTube shortcode][youtubeshortcode]:
```
```go-html-template
{{</* youtube 09jf3ow9jfw */>}}
```
@@ -244,7 +247,7 @@ Would be rendered as:
### Single Flexible Example: `vimeo`
```
```go-html-template
{{</* vimeo 49718712 */>}}
{{</* vimeo id="49718712" class="flex-video" */>}}
```
@@ -288,7 +291,7 @@ The following is taken from `highlight`, which is a [built-in shortcode][] that
The template for the `highlight` shortcode uses the following code, which is already included in Hugo:
```
```go-html-template
{{ .Get 0 | highlight .Inner }}
```
@@ -326,7 +329,7 @@ You also have an `img` shortcode with a single named `src` parameter that you wa
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" */>}}
@@ -336,7 +339,7 @@ You can then call your shortcode in your content as follows:
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">
@@ -344,7 +347,6 @@ This will output the following HTML. Note how the first two `img` shortcodes inh
<img src="/images/three.jpg">
```
## Error Handling in Shortcodes
Use the [errorf](/functions/errorf) template func and [.Position](/variables/shortcodes/) variable to get useful error messages in shortcodes:
@@ -366,12 +368,9 @@ ERROR 2018/11/07 10:05:55 missing value for param name: "/Users/bep/dev/go/gohug
More shortcode examples can be found in the [shortcodes directory for spf13.com][spfscs] and the [shortcodes directory for the Hugo docs][docsshortcodes].
## Inline Shortcodes
{{< new-in "0.52" >}}
Since Hugo 0.52, you can 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.
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 config:
@@ -398,7 +397,6 @@ The same inline shortcode can be reused later in the same content file, with dif
```go-text-template
{{</* time.inline /*/>}}
```
[basic content files]: /content-management/formats/ "See how Hugo leverages markdown--and other supported formats--to create content for your website."
[built-in shortcode]: /content-management/shortcodes/

View File

@@ -150,7 +150,7 @@ Weights of zero are thus treated specially: if two pages have unequal weights, a
Content can be assigned weight for each taxonomy that it's assigned to.
```
```txt
+++
tags = [ "a", "b", "c" ]
tags_weight = 22

View File

@@ -1,10 +1,8 @@
---
title: Template Debugging
# linktitle: Template Debugging
description: You can use Go templates' `printf` function to debug your Hugo templates. These snippets provide a quick and easy visualization of the variables available to you in different contexts.
date: 2017-02-01
publishdate: 2017-02-01
lastmod: 2017-02-01
categories: [templates]
keywords: [debugging,troubleshooting]
menu:
@@ -13,43 +11,38 @@ menu:
weight: 180
weight: 180
sections_weight: 180
draft: false
aliases: []
toc: false
---
Here are some snippets you can add to your template to answer some common questions.
These snippets use the `printf` function available in all Go templates. This function is an alias to the Go function, [fmt.Printf](https://golang.org/pkg/fmt/).
These snippets use the `printf` function available in all Go templates. This function is an alias to the Go function, [fmt.Printf](https://pkg.go.dev/fmt).
## What Variables are Available in this Context?
You can use the template syntax, `$.`, to get the top-level template context from anywhere in your template. This will print out all the values under, `.Site`.
```
```go-html-template
{{ printf "%#v" $.Site }}
```
This will print out the value of `.Permalink`:
```
```go-html-template
{{ printf "%#v" .Permalink }}
```
This will print out a list of all the variables scoped to the current context
(`.`, aka ["the dot"][tempintro]).
```
```go-html-template
{{ printf "%#v" . }}
```
When developing a [homepage][], what does one of the pages you're looping through look like?
```
```go-html-template
{{ range .Pages }}
{{/* The context, ".", is now each one of the pages as it goes through the loop */}}
{{ printf "%#v" . }}
@@ -60,13 +53,13 @@ When developing a [homepage][], what does one of the pages you're looping throug
Check that you are passing variables in the `partial` function:
```
```go-html-template
{{ partial "header.html" }}
```
This example will render the header partial, but the header partial will not have access to any contextual variables. You need to pass variables explicitly. For example, note the addition of ["the dot"][tempintro].
```
```go-html-template
{{ partial "header.html" . }}
```

View File

@@ -29,7 +29,7 @@ The following are common use cases for content views:
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
@@ -44,7 +44,7 @@ To create a new view, create a template in each of your different content type d
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
@@ -63,7 +63,7 @@ The following is the [lookup order][lookup] for content views:
## Example: Content View Inside a List
The following example demonstrates how to use content views inside of your [list templates][lists].
The following example demonstrates how to use content views inside your [list templates][lists].
### `list.html`