Merge commit 'd276e901b36d2576ef8350ed96b17f66254eac1b'

This commit is contained in:
Bjørn Erik Pedersen 2022-03-26 11:04:57 +02:00
commit d7497b28c1
No known key found for this signature in database
GPG key ID: 330E6E2BD4859D8F
28 changed files with 663 additions and 389 deletions

View file

@ -1,52 +1,89 @@
{ {
"version": "0.2", "version": "0.2",
"words": [ "words": [
"aaabaab",
"aabb", "aabb",
"aabba", "aabba",
"aabbaa", "aabbaa",
"aabbaabb", "aabbaabb",
"abourget", "abourget",
"absurl",
"adoc", "adoc",
"algolia", "algolia",
"allowfullscreen",
"ananke",
"anchorize", "anchorize",
"anthonyfok", "anthonyfok",
"asciidoctor", "asciidoctor",
"attrlink", "attrlink",
"azblob",
"baseof",
"beevelop",
"bibtex",
"Bjørn", "Bjørn",
"blackfriday", "blackfriday",
"blogue", "blogue",
"bogem", "bogem",
"Bootcamp",
"brlink",
"Brotli", "Brotli",
"Browsersync",
"canonify", "canonify",
"Catmull",
"Catwoman", "Catwoman",
"Cheatsheet", "Cheatsheet",
"choco",
"chromastyles", "chromastyles",
"clockoon", "clockoon",
"Cloudinary", "Cloudinary",
"CNAME", "CNAME",
"Codecademy's", "Codecademy's",
"CODEOWNERS", "CODEOWNERS",
"Coen",
"Commento", "Commento",
"Cond", "Cond",
"Contentful", "Contentful",
"copyrighthtml",
"corejs",
"countrunes", "countrunes",
"countwords", "countwords",
"crossreferences", "crossreferences",
"datatable",
"DATOCMS",
"debugconfig",
"DELIM",
"dhersam",
"digitalcraftsman", "digitalcraftsman",
"Disqus", "Disqus",
"Dmdh",
"doas",
"dokuwiki", "dokuwiki",
"dpkg",
"DRING", "DRING",
"Emojify", "Emojify",
"Enwrite", "Enwrite",
"eopkg",
"eparis", "eparis",
"errorf", "errorf",
"erroridf",
"Evernote",
"exitwp",
"Feminella",
"firstpost", "firstpost",
"Formspree",
"fpath",
"Francia", "Francia",
"freenode", "freenode",
"frontmatter",
"funcs", "funcs",
"funcsig", "funcsig",
"Garen", "Garen",
"gcloud",
"Getenv", "Getenv",
"getjson",
"getpage",
"Gmfc",
"Goel",
"Gohugo", "Gohugo",
"gohugoio", "gohugoio",
"goldenbridge", "goldenbridge",
@ -58,67 +95,142 @@
"Grayscale", "Grayscale",
"Gruber", "Gruber",
"gtag", "gtag",
"hidecaption",
"Hokus", "Hokus",
"hola",
"hügó",
"hugodeps",
"hugodoc", "hugodoc",
"Hugofy",
"hugolang", "hugolang",
"hugoversion", "hugoversion",
"Hyas",
"Hyvor", "Hyvor",
"iframes", "iframes",
"ifttt",
"iife",
"imgproc", "imgproc",
"importr",
"IMWQ",
"indice", "indice",
"innershortcode",
"Intelli", "Intelli",
"interdoc", "interdoc",
"IPTC", "IPTC",
"ismenucurrent",
"Isset", "Isset",
"Isso", "Isso",
"Jaco",
"johnpatitucci",
"Joomla", "Joomla",
"JRBR",
"jsonify", "jsonify",
"katex", "katex",
"keycdn",
"KEYVALS",
"kubernetes", "kubernetes",
"Lanczos",
"langformatnumber",
"lastmod", "lastmod",
"libwebp",
"linktitle", "linktitle",
"Lipi",
"lrwxr",
"maingo",
"markdownified", "markdownified",
"markdownify", "markdownify",
"mathjax", "mathjax",
"mdhender",
"mdshortcode",
"mercredi", "mercredi",
"Mittwoch", "Mittwoch",
"mkdir",
"mmark", "mmark",
"monokai", "monokai",
"Morling", "Morling",
"mspowerpoint",
"Multihost",
"Muut", "Muut",
"myclass",
"mydeployment",
"myindex",
"mylayout",
"mypage",
"mypartials", "mypartials",
"mypost", "mypost",
"mysite",
"myspa",
"mystyle",
"mytheme",
"NDJSON",
"needsexample", "needsexample",
"Netravali",
"newparam",
"Nikhil",
"Njjy",
"nlist",
"nobr", "nobr",
"nocopy", "nocopy",
"Norsk", "Norsk",
"nosniff",
"NOSQL",
"notoc",
"novembre", "novembre",
"NUMWORKERMULTIPLIER",
"Obhu",
"octohug",
"Octopress", "Octopress",
"oldparam",
"onrender",
"opengraph", "opengraph",
"OWASP", "OWASP",
"Pandoc", "Pandoc",
"partialcached",
"Pastorius",
"Patitucci",
"PCRE",
"peaceiris", "peaceiris",
"Pedersen", "Pedersen",
"permalinkable",
"plainify", "plainify",
"POSIX",
"postprocess",
"println", "println",
"publishdate", "publishdate",
"Pygments", "Pygments",
"querify", "querify",
"QVOMC",
"rdwatters",
"readfile", "readfile",
"rebinded",
"REDIR", "REDIR",
"reftext", "reftext",
"relatedfuncs", "relatedfuncs",
"relref", "relref",
"relurl",
"remarkjs", "remarkjs",
"rgba", "rgba",
"rlimit", "rlimit",
"roboto",
"rssxml",
"rwxrwxrwx",
"safehtml",
"safejs", "safejs",
"Samsa", "Samsa",
"Shekhar",
"Shortcode", "Shortcode",
"Shortcodes", "Shortcodes",
"Sindre", "Sindre",
"sitemapindex",
"sitemapxml",
"Smartcrop", "Smartcrop",
"Sprintf",
"Startseite",
"strconv",
"stringifier",
"struct", "struct",
"structs",
"subdir",
"Talkyard", "Talkyard",
"taxo", "taxo",
"tbody", "tbody",
@ -126,20 +238,29 @@
"testshortcodes", "testshortcodes",
"thead", "thead",
"Thinkful", "Thinkful",
"TLDR",
"TMPDIR", "TMPDIR",
"tojson", "tojson",
"Torikian", "Torikian",
"totoml", "totoml",
"toyaml", "toyaml",
"twitteruser",
"Unmarshal",
"Unmarshal", "Unmarshal",
"urlize", "urlize",
"urlset",
"vimrc", "vimrc",
"wanghc", "wanghc",
"Wappalyzer", "Wappalyzer",
"warnf", "warnf",
"webp", "webp",
"Wercker",
"wibble", "wibble",
"wordcount",
"workson", "workson",
"xvzf",
"yoyoyo",
"Zgotmpl",
"zzbbaabb" "zzbbaabb"
], ],
"language": "en,en-GB,en-US,de,fr", "language": "en,en-GB,en-US,de,fr",

View file

@ -17,7 +17,7 @@ toc: true
## GoAT Diagrams (Ascii) ## GoAT Diagrams (Ascii)
Hugo supports [GoAT](https://github.com/bep/goat) natively. This means that this code block: Hugo! supports [GoAT](https://github.com/bep/goat) natively. This means that this code block:
```` ````
```goat ```goat

View file

@ -4,7 +4,6 @@ linktitle: Content Formats
description: Both HTML and Markdown are supported content formats. description: Both HTML and Markdown are supported content formats.
date: 2017-01-10 date: 2017-01-10
publishdate: 2017-01-10 publishdate: 2017-01-10
lastmod: 2017-04-06
categories: [content management] categories: [content management]
keywords: [markdown,asciidoc,mmark,pandoc,content format] keywords: [markdown,asciidoc,mmark,pandoc,content format]
menu: menu:
@ -34,13 +33,12 @@ The current list of content formats in Hugo:
|MMark|mmark|Mmark is deprecated and will be removed in a future release.| |MMark|mmark|Mmark is deprecated and will be removed in a future release.|
|Emacs Org-Mode|org|See [go-org](https://github.com/niklasfasching/go-org).| |Emacs Org-Mode|org|See [go-org](https://github.com/niklasfasching/go-org).|
|AsciiDoc|asciidocext, adoc, ad|Needs [Asciidoctor][ascii] installed.| |AsciiDoc|asciidocext, adoc, ad|Needs [Asciidoctor][ascii] installed.|
|RST|rst|Needs [RST](http://docutils.sourceforge.net/rst.html) installed.| |RST|rst|Needs [RST](https://docutils.sourceforge.net/rst.html) installed.|
|Pandoc|pandoc, pdc|Needs [Pandoc](https://www.pandoc.org/) installed.| |Pandoc|pandoc, pdc|Needs [Pandoc](https://www.pandoc.org/) installed.|
|HTML|html, htm|To be treated as a content file, with layout, shortcodes etc., it must have front matter. If not, it will be copied as-is.| |HTML|html, htm|To be treated as a content file, with layout, shortcodes etc., it must have front matter. If not, it will be copied as-is.|
The `markup identifier` is fetched from either the `markup` variable in front matter or from the file extension. For markup-related configuration, see [Configure Markup](/getting-started/configuration-markup/). The `markup identifier` is fetched from either the `markup` variable in front matter or from the file extension. For markup-related configuration, see [Configure Markup](/getting-started/configuration-markup/).
## External Helpers ## External Helpers
Some of the formats in the table above need external helpers installed on your PC. For example, for AsciiDoc files, Some of the formats in the table above need external helpers installed on your PC. For example, for AsciiDoc files,
@ -149,7 +147,6 @@ Markdown syntax is simple enough to learn in a single sitting. The following are
[mdguide]: https://www.markdownguide.org/ [mdguide]: https://www.markdownguide.org/
[mdtutorial]: https://www.markdowntutorial.com/ [mdtutorial]: https://www.markdowntutorial.com/
[Miek Gieben's website]: https://miek.nl/2016/march/05/mmark-syntax-document/ [Miek Gieben's website]: https://miek.nl/2016/march/05/mmark-syntax-document/
[mmark]: https://github.com/mmarkdown/mmark
[org]: https://orgmode.org/ [org]: https://orgmode.org/
[pandoc]: https://www.pandoc.org/ [pandoc]: https://www.pandoc.org/
[rest]: https://docutils.sourceforge.io/rst.html [rest]: https://docutils.sourceforge.io/rst.html

View file

@ -1,8 +1,7 @@
--- ---
title: "Image Processing" title: "Image Processing"
description: "Image Page resources can be resized and cropped." description: "Resize, crop, rotate, filter, and convert images."
date: 2018-01-24T13:10:00-05:00 date: 2018-01-24T13:10:00-05:00
linktitle: "Image Processing"
categories: ["content management"] categories: ["content management"]
keywords: [resources, images] keywords: [resources, images]
weight: 4004 weight: 4004
@ -13,237 +12,334 @@ menu:
parent: "content-management" parent: "content-management"
weight: 32 weight: 32
--- ---
## Image Resources
## The Image Page Resource To process an image, you must access the image as either a page resource or a global resource.
The `image` is a [Page Resource]({{< relref "/content-management/page-resources" >}}), and the processing methods listed below do not work on images inside your `/static` folder. ### Page Resources
To print all images paths in a [Page Bundle]({{< relref "/content-management/organization#page-bundles" >}}): A page resource is a file within a [page bundle]. A page bundle is a directory with an `index.md` or `_index.md` file at its root.
```go-html-template
{{ with .Resources.ByType "image" }}
{{ range . }}
{{ .RelPermalink }}
{{ end }}
{{ end }}
```text
content/
└── posts/
└── post-1/ <-- page bundle
├── index.md
└── sunset.jpg <-- page resource
``` ```
## The Image Resource To access an image as a page resource:
The `image` resource can also be retrieved from a [global resource]({{< relref "/hugo-pipes/introduction#from-file-to-resource" >}})
```go-html-template ```go-html-template
{{- $image := resources.Get "images/logo.jpg" -}} {{ $image := .Resources.GetMatch "sunset.jpg" }}
```
### Global Resources
A global resource is a file:
- Within the `assets` directory, or
- Within any directory [mounted] to the `assets` directory, or
- Located on a remote server accessible via `http` or `https`
```text
assets/
└── images/
└── sunset.jpg <-- global resource
```
To access a local image as a global resource:
```go-html-template
{{ $image := resources.Get "images/sunset.jpg" }}
```
To access a remote image as a global resource:
```go-html-template
{{ $image := resources.GetRemote "https://gohugo.io/img/hugo-logo.png" }}
```
## Image Rendering
Once you have accessed an image as either a page resource or a global resource, render it in your templates using the `Permalink`, `RelPermalink`, `Width`, and `Height` properties.
Example 1: Throws an error if the resource is not found.
```go-html-template
{{ $image := .Resources.GetMatch "sunset.jpg" }}
<img src="{{ $image.RelPermalink }}" width="{{ $image.Width }}" height="{{ $image.Height }}">
```
Example 2: Skips image rendering if the resource is not found.
```go-html-template
{{ $image := .Resources.GetMatch "sunset.jpg" }}
{{ with $image }}
<img src="{{ .RelPermalink }}" width="{{ .Width }}" height="{{ .Height }}">
{{ end }}
```
Example 3: A more concise way to skip image rendering if the resource is not found.
```go-html-template
{{ with .Resources.GetMatch "sunset.jpg" }}
<img src="{{ .RelPermalink }}" width="{{ .Width }}" height="{{ .Height }}">
{{ end }}
``` ```
## Image Processing Methods ## Image Processing Methods
The `image` resource implements the `Resize`, `Fit`, `Fill`, `Crop`, and `Filter` methods, each returning a transformed image using the specified dimensions and processing options. The `image` resource implements the `Resize`, `Fit`, `Fill`, `Crop`, `Filter`, and `Exif` methods.
{{% note %}} {{% note %}}
Metadata (EXIF, IPTC, XMP, etc.) is not preserved during image transformation. Use the [`Exif`](#exif) method with the _original_ image to extract EXIF metadata from JPEG or TIFF images. Metadata (Exif, IPTC, XMP, etc.) is not preserved during image transformation. Use the`Exif` method with the _original_ image to extract Exif metadata from JPEG or TIFF images.
{{% /note %}} {{% /note %}}
### Resize ### Resize
Resizes the image to the specified width and height. Resize an image to the specified width and/or height.
```go If you specify both width and height, the resulting image will be disproportionally scaled unless the original image has the same aspect ratio.
// Resize to a width of 600px and preserve ratio
{{ $image := $resource.Resize "600x" }}
// Resize to a height of 400px and preserve ratio ```go-html-template
{{ $image := $resource.Resize "x400" }} {{/* Resize to a width of 600px and preserve aspect ratio */}}
{{ $image := $image.Resize "600x" }}
// Resize to a width 600px and a height of 400px {{/* Resize to a height of 400px and preserve aspect ratio */}}
{{ $image := $resource.Resize "600x400" }} {{ $image := $image.Resize "x400" }}
{{/* Resize to a width of 600px and a height of 400px */}}
{{ $image := $image.Resize "600x400" }}
``` ```
### Fit ### Fit
Scale down the image to fit the given dimensions while maintaining aspect ratio. Both height and width are required. Downscale an image to fit the given dimensions while maintaining aspect ratio. You must provide both width and height.
```go ```go-html-template
{{ $image := $resource.Fit "600x400" }} {{ $image := $image.Fit "600x400" }}
``` ```
### Fill ### Fill
Crop and resize the image to match the given dimensions. Both height and width are required. Crop and resize an image to match the given dimensions. You must provide both width and height. Use the [`anchor`] option to change the crop box anchor point.
```go ```go-html-template
{{ $image := $resource.Fill "600x400" }} {{ $image := $image.Fill "600x400" }}
``` ```
### Crop ### Crop
Crop the image to match the given dimensions without resizing. Both height and width are required. Crop an image to match the given dimensions without resizing. You must provide both width and height. Use the [`anchor`] option to change the crop box anchor point.
```go ```go-html-template
{{ $image := $resource.Crop "400x400" }} {{ $image := $image.Crop "600x400" }}
``` ```
### Filter ### Filter
Apply one or more filters to your image. See [Image Filters](/functions/images/#image-filters) for a full list. Apply one or more [filters] to an image.
```go-html-template ```go-html-template
{{ $img = $img.Filter (images.GaussianBlur 6) (images.Pixelate 8) }} {{ $image := $image.Filter (images.GaussianBlur 6) (images.Pixelate 8) }}
``` ```
The above can also be written in a more functional style using pipes: Write this in a more functional style using pipes. Hugo applies the filters in the order given.
```go-html-template ```go-html-template
{{ $img = $img | images.Filter (images.GaussianBlur 6) (images.Pixelate 8) }} {{ $image := $image | images.Filter (images.GaussianBlur 6) (images.Pixelate 8) }}
``` ```
The filters will be applied in the given order. Sometimes it can be useful to create the filter chain once and then reuse it.
Sometimes it can be useful to create the filter chain once and then reuse it:
```go-html-template ```go-html-template
{{ $filters := slice (images.GaussianBlur 6) (images.Pixelate 8) }} {{ $filters := slice (images.GaussianBlur 6) (images.Pixelate 8) }}
{{ $img1 = $img1.Filter $filters }} {{ $image1 := $image1.Filter $filters }}
{{ $img2 = $img2.Filter $filters }} {{ $image2 := $image2.Filter $filters }}
``` ```
### Exif ### Exif
Provides an [Exif](https://en.wikipedia.org/wiki/Exif) object with metadata about the image. Provides an [Exif] object containing image metadata.
Note that this is only supported for JPEG and TIFF images, so it's recommended to wrap the access with a `with`, e.g.: You may access Exif data in JPEG and TIFF images. To prevent errors when processing images without Exif data, wrap the access in a `with` statement.
```go-html-template ```go-html-template
{{ with $img.Exif }} {{ with $image.Exif }}
Date: {{ .Date }} Date: {{ .Date }}
Lat/Long: {{ .Lat}}/{{ .Long }} Lat/Long: {{ .Lat }}/{{ .Long }}
Tags: Tags:
{{ range $k, $v := .Tags }} {{ range $k, $v := .Tags }}
TAG: {{ $k }}: {{ $v }} TAG: {{ $k }}: {{ $v }}
{{ end }} {{ end }}
{{ end }} {{ end }}
``` ```
Or individually access EXIF data with dot access, e.g.: You may also access Exif fields individually, using the [`lang.FormatNumber`] function to format the fields as needed.
```go-html-template ```go-html-template
{{ with $src.Exif }} {{ with $image.Exif }}
<ul> <ul>
{{ with .Date }}<li>Date: {{ .Format "January 02, 2006" }}</li>{{ end }} {{ with .Date }}<li>Date: {{ .Format "January 02, 2006" }}</li>{{ end }}
{{ with .Tags.ApertureValue }}<li>Aperture: {{ lang.NumFmt 2 . }}</li>{{ end }} {{ with .Tags.ApertureValue }}<li>Aperture: {{ lang.FormatNumber 2 . }}</li>{{ end }}
{{ with .Tags.BrightnessValue }}<li>Brightness: {{ lang.NumFmt 2 . }}</li>{{ end }} {{ with .Tags.BrightnessValue }}<li>Brightness: {{ lang.FormatNumber 2 . }}</li>{{ end }}
{{ with .Tags.ExposureTime }}<li>Exposure Time: {{ . }}</li>{{ end }} {{ with .Tags.ExposureTime }}<li>Exposure Time: {{ . }}</li>{{ end }}
{{ with .Tags.FNumber }}<li>F Number: {{ . }}</li>{{ end }} {{ with .Tags.FNumber }}<li>F Number: {{ . }}</li>{{ end }}
{{ with .Tags.FocalLength }}<li>Focal Length: {{ . }}</li>{{ end }} {{ with .Tags.FocalLength }}<li>Focal Length: {{ . }}</li>{{ end }}
{{ with .Tags.ISOSpeedRatings }}<li>ISO Speed Ratings: {{ . }}</li>{{ end }} {{ with .Tags.ISOSpeedRatings }}<li>ISO Speed Ratings: {{ . }}</li>{{ end }}
{{ with .Tags.LensModel }}<li>Lens Model: {{ . }}</li>{{ end }} {{ with .Tags.LensModel }}<li>Lens Model: {{ . }}</li>{{ end }}
</ul> </ul>
{{ end }} {{ end }}
``` ```
Some fields may need to be formatted with [`lang.FormatNumberCustom`]({{< relref "functions/lang" >}}) function to prevent display like `Aperture: 2.278934289` instead of `Aperture: 2.28`. #### Exif Variables
#### Exif fields .Date
: Image creation date/time. Format with the [time.Format] function.
Date .Lat
: "photo taken" date/time : GPS latitude in degrees.
Lat .Long
: "photo taken where", GPS latitude : GPS longitude in degrees.
Long .Tags
: "photo taken where", GPS longitude : A collection of the available Exif tags for this image. You may include or exclude specific tags from this collection in the [site configuration](#exif-data).
See [Image Processing Config](#image-processing-config) for how to configure what gets included in Exif.
## Image Processing Options ## Image Processing Options
In addition to the dimensions (e.g. `600x400`), Hugo supports a set of additional image options. The `Resize`, `Fit`, `Fill`, and `Crop` methods accept a space-separated, case-insensitive list of options. The order of the options within the list is irrelevant.
### Background Color ### Dimensions
The background color to fill into the transparency layer. This is mostly useful when converting to a format that does not support transparency, e.g. `JPEG`. With the `Resize` method you must specify width, height, or both. The `Fit`, `Fill`, and `Crop` methods require both width and height. All dimensions are in pixels.
You can set the background color to use with a 3 or 6 digit hex code starting with `#`. ```go-html-template
{{ $image := $image.Resize "600x" }}
```go {{ $image := $image.Resize "x400" }}
{{ $image.Resize "600x jpg #b31280" }} {{ $image := $image.Resize "600x400" }}
{{ $image := $image.Fit "600x400" }}
{{ $image := $image.Fill "600x400" }}
{{ $image := $image.Crop "600x400" }}
``` ```
For color codes, see https://www.google.com/search?q=color+picker ### Rotation
**Note** that you also set a default background color to use, see [Image Processing Config](#image-processing-config). Rotates an image counter-clockwise by the given angle. Hugo performs rotation _before_ scaling. For example, if the original image is 600x400 and you wish to rotate the image 90 degrees counter-clockwise while scaling it by 50%:
### JPEG and WebP Quality ```go-html-template
{{ $image = $image.Resize "200x r90" }}
Only relevant for JPEG and WebP images, values 1 to 100 inclusive, higher is better. Default is 75.
```go
{{ $image.Resize "600x q50" }}
``` ```
{{< new-in "0.83.0" >}} WebP support was added in Hugo 0.83.0. In the example above, the width represents the desired width _after_ rotation.
### Hint To rotate an image without scaling, use the dimensions of the original image:
{{< new-in "0.83.0" >}} ```go-html-template
{{ with .Resources.GetMatch "sunset.jpg" }}
{{< new-in "0.83.0" >}} {{ with .Resize (printf "%dx%d r90" .Height .Width) }}
<img src="{{ .RelPermalink }}" width="{{ .Width }}" height="{{ .Height }}">
Hint about what type of image this is. Currently only used when encoding to WebP. {{ end }}
{{ end }}
Default value is `photo`.
Valid values are `picture`, `photo`, `drawing`, `icon`, or `text`.
```go
{{ $image.Resize "600x webp drawing" }}
``` ```
### Rotate In the example above, on the second line, we have reversed width and height to reflect the desired dimensions _after_ rotation.
Rotates an image by the given angle counter-clockwise. The rotation will be performed first to get the dimensions correct. The main use of this is to be able to manually correct for [EXIF orientation](https://github.com/golang/go/issues/4341) of JPEG images.
```go
{{ $image.Resize "600x r90" }}
```
### Anchor ### Anchor
Only relevant for the `Crop` and `Fill` methods. This is useful for thumbnail generation where the main motive is located in, say, the left corner. When using the `Crop` or `Fill` method, the _anchor_ determines the placement of the crop box. You may specify `TopLeft`, `Top`, `TopRight`, `Left`, `Center`,`Right`, `BottomLeft`, `Bottom`, `BottomRight`, or `Smart`.
Valid values are `Smart`, `Center`, `TopLeft`, `Top`, `TopRight`, `Left`, `Right`, `BottomLeft`, `Bottom`, `BottomRight`. The default value is `Smart`, which uses [Smartcrop] image analysis to determine the optimal placement of the crop box. You may override the default value in the [site configuration](#processing-options).
Default value is `Smart`, which uses [Smartcrop](https://github.com/muesli/smartcrop) to determine the best crop. For example, if you have a 400x200 image with a bird in the upper left quadrant, you can create a 200x100 thumbnail containing the bird:
```go ```go-html-template
{{ $image.Fill "300x200 BottomLeft" }} {{ $image.Crop "200x100 TopLeft" }}
``` ```
### Resample Filter If you apply rotation when using the `Crop` or `Fill` method, specify the anchor relative to the rotated image.
Filter used in resizing. Default is `Box`, a simple and fast resampling filter appropriate for downscaling.
Examples are: `Box`, `NearestNeighbor`, `Linear`, `Gaussian`.
See https://github.com/disintegration/imaging for more. If you want to trade quality for faster processing, this may be a option to test.
```go
{{ $image.Resize "600x400 Gaussian" }}
```
### Target Format ### Target Format
By default the images is encoded in the source format, but you can set the target format as an option. By default, Hugo encodes the image in the source format. You may convert the image to another format by specifying `bmp`, `gif`, `jpeg`, `jpg`, `png`, `tif`, `tiff`, or `webp`.
Valid values are `bmp`, `gif`, `jpeg`, `jpg`, `png`, `tif`, `tiff`, and `webp`. ```go-html-template
{{ $image.Resize "600x webp" }}
```go
{{ $image.Resize "600x jpg" }}
``` ```
{{< new-in "0.83.0" >}} WebP support was added in Hugo 0.83.0. To convert an image without scaling, use the dimensions of the original image:
```go-html-template
{{ with .Resources.GetMatch "sunset.jpg" }}
{{ with .Resize (printf "%dx%d webp" .Width .Height) }}
<img src="{{ .RelPermalink }}" width="{{ .Width }}" height="{{ .Height }}">
{{ end }}
{{ end }}
```
### Quality
Applicable to JPEG and WebP images, the `q` value determines the quality of the converted image. Higher values produce better quality images, while lower values produce smaller files. Set this value to a whole number between 1 and 100, inclusive.
The default value is 75. You may override the default value in the [site configuration](#processing-options).
```go-html-template
{{ $image.Resize "600x webp q50" }}
```
### Hint
<!-- Specifies a libwebp preset, not a libwebp image hint. -->
Applicable to WebP images, this option corresponds to a set of pre-defined encoding parameters.
Value|Example
:--|:--
`drawing`|Hand or line drawing with high-contrast details
`icon`|Small colorful image
`photo`|Outdoor photograph with natural lighting
`picture`|Indoor photograph such as a portrait
`text`|Image that is primarily text
The default value is `photo`. You may override the default value in the [site configuration](#processing-options).
```go-html-template
{{ $image.Resize "600x webp picture" }}
```
### Background Color
When converting an image from a format that supports transparency (e.g., PNG) to a format that does _not_ support transparency (e.g., JPEG), you may specify the background color of the resulting image.
Use either a 3-digit or a 6-digit hexadecimal color code (e.g., `#00f` or `#0000ff`).
The default value is `#ffffff` (white). You may override the default value in the [site configuration](#processing-options).
```go-html-template
{{ $image.Resize "600x jpg #b31280" }}
```
### Resampling Filter
You may specify the resampling filter used when resizing an image. Commonly used resampling filters include:
Filter|Description
:--|:--
`Box`|Simple and fast averaging filter appropriate for downscaling
`Lanczos`|High-quality resampling filter for photographic images yielding sharp results
`CatmullRom`|Sharp cubic filter that is faster than the Lanczos filter while providing similar results
`MitchellNetravali`|Cubic filter that produces smoother results with less ringing artifacts than CatmullRom
`Linear`|Bilinear resampling filter, produces smooth output, faster than cubic filters
`NearestNeighbor`|Fastest resampling filter, no antialiasing
The default value is `Box`. You may override the default value in the [site configuration](#processing-options).
```go-html-template
{{ $image.Resize "600x400 Lanczos" }}
```
See [github.com/disintegration/imaging] for the complete list of resampling filters. If you wish to improve image quality at the expense of performance, you may wish to experiment with the alternative filters.
## Image Processing Examples ## Image Processing Examples
@ -261,79 +357,83 @@ _The photo of the sunset used in the examples below is Copyright [Bjørn Erik Pe
{{< imgproc sunset Resize "300x q10" />}} {{< imgproc sunset Resize "300x q10" />}}
This is the shortcode used in the examples above: This is the shortcode used to generate the examples above:
{{< code file="layouts/shortcodes/imgproc.html" >}} {{< code file="layouts/shortcodes/imgproc.html" >}}
{{< readfile file="layouts/shortcodes/imgproc.html" >}} {{< readfile file="layouts/shortcodes/imgproc.html" >}}
{{< /code >}} {{< /code >}}
And it is used like this: Call the shortcode from your markdown like this:
```go-html-template ```go-html-template
{{</* imgproc sunset Resize "300x" /*/>}} {{</* imgproc sunset Resize "300x" /*/>}}
``` ```
{{% note %}} {{% note %}}
**Tip:** Note the self-closing shortcode syntax above. The `imgproc` shortcode can be called both with and without **inner content**. Note the self-closing shortcode syntax above. You may call the `imgproc` shortcode with or without **inner content**.
{{% /note %}} {{% /note %}}
## Image Processing Config ## Imaging Configuration
You can configure an `imaging` section in `config.toml` with default image processing options: ### Processing Options
```toml Define an `imaging` section in your site configuration to set the default [image processing options](#image-processing-options).
{{< code-toggle file="config" copy=true >}}
[imaging] [imaging]
# Default resample filter used for resizing. Default is Box, resampleFilter = "Box"
# a simple and fast averaging filter appropriate for downscaling.
# See https://github.com/disintegration/imaging
resampleFilter = "box"
# Default JPEG or WebP quality setting. Default is 75.
quality = 75 quality = 75
# Default hint about what type of image. Currently only used for WebP encoding.
# Default is "photo".
# Valid values are "picture", "photo", "drawing", "icon", or "text".
hint = "photo" hint = "photo"
anchor = "Smart"
# Anchor used when cropping pictures with either .Fill or .Crop
# Default is "smart" which does Smart Cropping, using https://github.com/muesli/smartcrop
# Smart Cropping is content aware and tries to find the best crop for each image.
# Valid values are Smart, Center, TopLeft, Top, TopRight, Left, Right, BottomLeft, Bottom, BottomRight
anchor = "smart"
# Default background color.
# Hugo will preserve transparency for target formats that supports it,
# but will fall back to this color for JPEG.
# Expects a standard HEX color string with 3 or 6 digits.
# See https://www.google.com/search?q=color+picker
bgColor = "#ffffff" bgColor = "#ffffff"
{{< /code-toggle >}}
anchor
: See image processing options: [anchor](#anchor).
bgColor
: See image processing options: [background color](#background-color).
hint
: See image processing options: [hint](#hint).
quality
: See image processing options: [quality](#quality).
resampleFilter
: See image processing options: [resampling filter](#resampling-filter).
### Exif Data
Define an `imaging.exif` section in your site configuration to control the availability of Exif data.
{{< code-toggle file="config" copy=true >}}
[imaging.exif] [imaging.exif]
# Regexp matching the fields you want to Exclude from the (massive) set of Exif info
# available. As we cache this info to disk, this is for performance and
# disk space reasons more than anything.
# If you want it all, put ".*" in this config setting.
# Note that if neither this or ExcludeFields is set, Hugo will return a small
# default set: GPS|Exif|Exposure[M|P|B]|Contrast|Resolution|Sharp|JPEG|Metering|Sensing|Saturation|ColorSpace|Flash|WhiteBalance
includeFields = "" includeFields = ""
# Regexp matching the Exif fields you want to exclude. This may be easier to use
# than IncludeFields above, depending on what you want.
excludeFields = "" excludeFields = ""
# Hugo extracts the "photo taken" date/time into .Date by default.
# Set this to true to turn it off.
disableDate = false disableDate = false
# Hugo extracts the "photo taken where" (GPS latitude and longitude) into
# .Long and .Lat. Set this to true to turn it off.
disableLatLong = false disableLatLong = false
``` {{< /code-toggle >}}
disableDate
: Hugo extracts the image creation date/time into `.Date`. Set this to `true` to disable. Default is `false`.
disableLatLong
: Hugo extracts the GPS latitude and longitude into `.Lat` and `.Long`. Set this to `true` to disable. Default is `false`.
excludeFields
: Regular expression matching the Exif tags to exclude from the `.Tags` collection. Default is&nbsp;`""`.
includeFields
: Regular expression matching the Exif tags to include in the `.Tags` collection. Default is&nbsp;`""`. To include all available tags, set this value to&nbsp;`".*"`.
{{% note %}}
To improve performance and decrease cache size, if you set neither `excludeFields` nor `includeFields`, Hugo excludes the following tags: `ColorSpace`, `Contrast`, `Exif`, `Exposure[M|P|B]`, `Flash`, `GPS`, `JPEG`, `Metering`, `Resolution`, `Saturation`, `Sensing`, `Sharp`, and `WhiteBalance`.
{{% /note %}}
## Smart Cropping of Images ## Smart Cropping of Images
By default, Hugo will use [Smartcrop](https://github.com/muesli/smartcrop), a library created by [muesli](https://github.com/muesli), when cropping images with `.Fill` or `.Crop`. You can set the anchor point manually, but in most cases the smart option will make a good choice. And we will work with the library author to improve this in the future. By default, Hugo uses the [Smartcrop] library when cropping images with the `Crop` or`Fill` methods. You can set the anchor point manually, but in most cases the `Smart` option will make a good choice.
Examples using the sunset image from above: Examples using the sunset image from above:
@ -343,16 +443,20 @@ Examples using the sunset image from above:
## Image Processing Performance Consideration ## Image Processing Performance Consideration
Processed images are stored below `<project-dir>/resources` (can be set with `resourceDir` config setting). This folder is deliberately placed in the project, as it is recommended to check these into source control as part of the project. These images are not "Hugo fast" to generate, but once generated they can be reused. Hugo caches processed images in the `resources` directory. If you include this directory in source control, Hugo will not have to regenerate the images in a CI/CD workflow (e.g., GitHub Pages, GitLab Pages, Netlify, etc.). This results in faster builds.
If you change your image settings (e.g. size), remove or rename images etc., you will end up with unused images taking up space and cluttering your project. If you change image processing methods or options, or if you rename or remove images, the `resources` directory will contain unused images. To remove the unused images, perform garbage collection with:
To clean up, run:
```bash ```bash
hugo --gc hugo --gc
``` ```
{{% note %}} [`anchor`]: {{< relref "content-management/image-processing#anchor" >}}
**GC** is short for **Garbage Collection**. [`lang.FormatNumber`]: {{< relref "functions/lang#langformatnumber" >}}
{{% /note %}} [Exif]: <https://en.wikipedia.org/wiki/Exif>
[filters]: {{< relref "functions/images" >}}
[github.com/disintegration/imaging]: <https://github.com/disintegration/imaging#image-resizing>
[mounted]: {{< relref "hugo-modules/configuration#module-config-mounts">}}
[page bundle]: {{< relref "content-management/page-bundles" >}}
[Smartcrop]: <https://github.com/muesli/smartcrop#smartcrop>
[time.Format]: {{< relref "functions/dateformat" >}}

View file

@ -42,14 +42,14 @@ Here is the list of "Related" methods available on a page collection such `.Regu
Returns a collection of pages related the given one. Returns a collection of pages related the given one.
``` ```
{{ $related := .Site.RegularPages.Related . }} {{ $related := site.RegularPages.Related . }}
``` ```
#### .RelatedIndices PAGE INDICE1 [INDICE2 ...] #### .RelatedIndices PAGE INDICE1 [INDICE2 ...]
Returns a collection of pages related to a given one restricted to a list of indices. Returns a collection of pages related to a given one restricted to a list of indices.
``` ```
{{ $related := .Site.RegularPages.RelatedIndices . "tags" "date" }} {{ $related := site.RegularPages.RelatedIndices . "tags" "date" }}
``` ```
#### .RelatedTo KEYVALS [KEYVALS2 ...] #### .RelatedTo KEYVALS [KEYVALS2 ...]
@ -58,7 +58,7 @@ Returns a collection of pages related together by a set of indices and their mat
In order to build those set and pass them as argument, one must use the `keyVals` function where the first argument would be the `indice` and the consecutive ones its potential `matches`. In order to build those set and pass them as argument, one must use the `keyVals` function where the first argument would be the `indice` and the consecutive ones its potential `matches`.
``` ```
{{ $related := .Site.RegularPages.RelatedTo ( keyVals "tags" "hugo" "rocks") ( keyVals "date" .Date ) }} {{ $related := site.RegularPages.RelatedTo ( keyVals "tags" "hugo" "rocks") ( keyVals "date" .Date ) }}
``` ```
{{% note %}} {{% note %}}

View file

@ -178,6 +178,7 @@ Assuming a `baseURL` of `example.com`, the contents of the auto-generated alias
The `http-equiv="refresh"` line is what performs the redirect, in 0 seconds in this case. If an end user of your website goes to `https://example.com/posts/my-old-url`, they will now be automatically redirected to the newer, correct URL. The addition of `<meta name="robots" content="noindex">` lets search engine bots know that they should not crawl and index your new alias page. The `http-equiv="refresh"` line is what performs the redirect, in 0 seconds in this case. If an end user of your website goes to `https://example.com/posts/my-old-url`, they will now be automatically redirected to the newer, correct URL. The addition of `<meta name="robots" content="noindex">` lets search engine bots know that they should not crawl and index your new alias page.
### Customize ### Customize
You may customize this alias page by creating an `alias.html` template in the You may customize this alias page by creating an `alias.html` template in the
layouts folder of your site (i.e., `layouts/alias.html`). In this case, the data passed to the template is layouts folder of your site (i.e., `layouts/alias.html`). In this case, the data passed to the template is

View file

@ -424,7 +424,7 @@ Feel free to [open an issue][newissue] if you think you found a bug or you have
[docscontrib]: /contribute/documentation/ [docscontrib]: /contribute/documentation/
[forums]: https://discourse.gohugo.io [forums]: https://discourse.gohugo.io
[gitbook]: https://git-scm.com/ [gitbook]: https://git-scm.com/
[gobootcamp]: http://www.golangbootcamp.com/book/get_setup [gobootcamp]: https://www.golangbootcamp.com/book/get_setup
[godl]: https://golang.org/dl/ [godl]: https://golang.org/dl/
[goinstall]: https://golang.org/doc/install [goinstall]: https://golang.org/doc/install
[gvm]: https://github.com/moovweb/gvm [gvm]: https://github.com/moovweb/gvm

View file

@ -17,11 +17,11 @@ If [Goldmark](https://gohugo.io/getting-started/configuration-markup#goldmark) i
Since the `defaultMarkdownHandler` and this template function use the same sanitizing logic, you can use the latter to determine the ID of a header for linking with anchor tags. Since the `defaultMarkdownHandler` and this template function use the same sanitizing logic, you can use the latter to determine the ID of a header for linking with anchor tags.
``` ```go-html-template
{{anchorize "This is a header"}} → "this-is-a-header" {{ anchorize "This is a header" }} --> "this-is-a-header"
{{anchorize "This is also a header"}} → "this-is-also-a-header" {{ anchorize "This is also a header" }} --> "this-is-also----a-header"
{{anchorize "main.go"}} → "main-go" {{ anchorize "main.go" }} --> "maingo"
{{anchorize "Article 123"}} → "article-123" {{ anchorize "Article 123" }} --> "article-123"
{{anchorize "<- Let's try this, shall we?"}} "let-s-try-this-shall-we" {{ anchorize "<- Let's try this, shall we?" }} --> "--lets-try-this-shall-we"
{{anchorize "Hello, 世界"}} → "hello-世界" {{ anchorize "Hello, 世界" }} --> "hello-世界"
``` ```

View file

@ -25,14 +25,9 @@ An example appending single values:
The same example appending a slice to a slice: The same example appending a slice to a slice:
```go-html-template ```go-html-template
{{ $s := slice "a" "b" "c" }} {{ $s := slice "a" "b" "c" }}
{{ $s = $s | append (slice "d" "e") }} {{ $s = $s | append (slice "d" "e") }}
``` ```
The `append` function works for all types, including `Pages`. The `append` function works for all types, including `Pages`.

View file

@ -64,13 +64,13 @@ If you have `post-tag-list.html` and `post-tag-link.html` as [partials][], you *
Tags: Tags:
{{ $len := len . }} {{ $len := len . }}
{{ if eq $len 1 }} {{ if eq $len 1 }}
{{ partial "post-tag-link" (index . 0) }} {{ partial "post-tag-link.html" (index . 0) }}
{{ else }} {{ else }}
{{ $last := sub $len 1 }} {{ $last := sub $len 1 }}
{{ range first $last . }} {{ range first $last . }}
{{ partial "post-tag-link" . }}, {{ partial "post-tag-link.html" . }},
{{ end }} {{ end }}
{{ partial "post-tag-link" (index . $last) }} {{ partial "post-tag-link.html" (index . $last) }}
{{ end }} {{ end }}
</div> </div>
{{ end }} {{ end }}
@ -89,7 +89,7 @@ This first version of `layouts/partials/post-tag-list.html` separates all of the
<div class="tags-list"> <div class="tags-list">
Tags: Tags:
{{ $sort := sort . }} {{ $sort := sort . }}
{{ $links := apply $sort "partial" "post-tag-link" "." }} {{ $links := apply $sort "partial" "post-tag-link.html" "." }}
{{ $clean := apply $links "chomp" "." }} {{ $clean := apply $links "chomp" "." }}
{{ delimit $clean ", " }} {{ delimit $clean ", " }}
</div> </div>
@ -102,7 +102,7 @@ Now in the completed version, you can sort the tags, convert the tags to links w
{{ with .Params.tags }} {{ with .Params.tags }}
<div class="tags-list"> <div class="tags-list">
Tags: Tags:
{{ delimit (apply (apply (sort .) "partial" "post-tag-link" ".") "chomp" ".") ", " }} {{ delimit (apply (apply (sort .) "partial" "post-tag-link.html" ".") "chomp" ".") ", " }}
</div> </div>
{{ end }} {{ end }}
{{< /code >}} {{< /code >}}

View file

@ -28,10 +28,4 @@ hugoversion: "0.49"
{{ end }} {{ end }}
{{< /code >}} {{< /code >}}
The page group you get from `group` is of the same type you get from the built-in [group methods](/templates/lists#group-content) in Hugo. The above example can even be [paginated](/templates/pagination/#list-paginator-pages). The page group you get from `group` is of the same type you get from the built-in [group methods](/templates/lists#group-content) in Hugo. The above example can even be [paginated](/templates/pagination/#list-paginator-pages).

View file

@ -4,7 +4,6 @@ linktitle: hugo
description: The `hugo` function provides easy access to Hugo-related data. description: The `hugo` function provides easy access to Hugo-related data.
date: 2019-01-31 date: 2019-01-31
publishdate: 2019-01-31 publishdate: 2019-01-31
lastmod: 2019-01-31
keywords: [] keywords: []
categories: [functions] categories: [functions]
menu: menu:
@ -60,7 +59,7 @@ hugo.Deps
`hugo.Deps` returns a list of dependencies for a project (either Hugo Modules or local theme components). `hugo.Deps` returns a list of dependencies for a project (either Hugo Modules or local theme components).
Eeach dependency contains: Each dependency contains:
Path (string) Path (string)
: Returns the path to this module. This will either be the module path, e.g. "github.com/gohugoio/myshortcodes", or the path below your /theme folder, e.g. "mytheme". : Returns the path to this module. This will either be the module path, e.g. "github.com/gohugoio/myshortcodes", or the path below your /theme folder, e.g. "mytheme".

View file

@ -3,7 +3,6 @@ title: relURL
description: Creates a baseURL-relative URL. description: Creates a baseURL-relative URL.
date: 2017-02-01 date: 2017-02-01
publishdate: 2017-02-01 publishdate: 2017-02-01
lastmod: 2017-02-01
categories: [functions] categories: [functions]
menu: menu:
docs: docs:
@ -31,7 +30,7 @@ The last two examples may look strange but can be very useful. For example, the
{{< code file="layouts/partials/schemaorg-metadata.html" download="schemaorg-metadata.html" >}} {{< code file="layouts/partials/schemaorg-metadata.html" download="schemaorg-metadata.html" >}}
<script type="application/ld+json"> <script type="application/ld+json">
{ {
"@context" : "http://schema.org", "@context" : "https://schema.org",
"@type" : "BlogPosting", "@type" : "BlogPosting",
"image" : {{ apply .Params.images "absURL" "." }} "image" : {{ apply .Params.images "absURL" "." }}
} }
@ -46,5 +45,5 @@ The above uses the [apply function][] and also exposes how the Go template parse
[apply function]: /functions/apply/ [apply function]: /functions/apply/
[configuration]: /getting-started/configuration/ [configuration]: /getting-started/configuration/
[jsonld]: https://developers.google.com/search/docs/guides/intro-structured-data [jsonld]: https://developers.google.com/search/docs/advanced/structured-data/intro-structured-data
[safejs]: /functions/safejs [safejs]: /functions/safejs

View file

@ -23,7 +23,7 @@ If `SUBSTR` is an empty string, this function returns 1 plus the number of Unico
Example|Result Example|Result
:--|:-- :--|:--
`{{ "aaabaab" | strings.Count "a" }}`|5 `{{ "aaabaab" \| strings.Count "a" }}`|5
`{{ "aaabaab" | strings.Count "aa" }}`|2 `{{ "aaabaab" \| strings.Count "aa" }}`|2
`{{ "aaabaab" | strings.Count "aaa" }}`|1 `{{ "aaabaab" \| strings.Count "aaa" }}`|1
`{{ "aaabaab" | strings.Count "" }}`|8 `{{ "aaabaab" \| strings.Count "" }}`|8

View file

@ -119,119 +119,5 @@ ordered
## Markdown Render Hooks ## Markdown Render Hooks
{{< new-in "0.62.0" >}} See [Markdown Render Hooks](/templates/render-hooks/).
Note that this is only supported with the [Goldmark](#goldmark) renderer.
Render Hooks allow custom templates to override markdown rendering functionality. You can do this by creating templates with base names `render-{feature}` 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" >}}
The features currently supported are:
* `image`
* `link`
* `heading` {{< new-in "0.71.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:
```bash
layouts
└── _default
└── _markup
├── 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 Hook Templates
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.
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) {{< new-in "0.82.0" >}}
: A map of attributes (e.g. `id`, `class`)
#### 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://d33wubrfki0l68.cloudfront.net/c38c7334cc3f23585738e40334284fddcaf03d5e/2e17c/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>
```

View file

@ -310,12 +310,21 @@ See [Configure Minify](#configure-minify)
Module config see [Module Config](/hugo-modules/configuration/).{{< new-in "0.56.0" >}} Module config see [Module Config](/hugo-modules/configuration/).{{< new-in "0.56.0" >}}
### newContentEditor ### newContentEditor
**Default value:** ""
The editor to use when creating new content. The editor to use when creating new content.
### noChmod ### noChmod
**Default value:** false
Don't sync permission mode of files. Don't sync permission mode of files.
### noTimes ### noTimes
**Default value:** false
Don't sync modification time of files. Don't sync modification time of files.
### outputFormats ### outputFormats
@ -352,6 +361,9 @@ The directory to where Hugo will write the final static site (the HTML files etc
: See [Related Content](/content-management/related/#configure-related-content).{{< new-in "0.27" >}} : See [Related Content](/content-management/related/#configure-related-content).{{< new-in "0.27" >}}
### relativeURLs ### relativeURLs
**Default value:** false
Enable this to make all relative URLs relative to content root. Note that this does not affect absolute URLs. Enable this to make all relative URLs relative to content root. Note that this does not affect absolute URLs.
### refLinksErrorLevel ### refLinksErrorLevel
@ -376,6 +388,8 @@ content/post/hügó.md --> https://example.org/post/hugo/
### rssLimit ### rssLimit
**Default value:** -1 (unlimited)
Maximum number of items in the RSS feed. Maximum number of items in the RSS feed.
### sectionPagesMenu ### sectionPagesMenu
@ -432,6 +446,8 @@ When enabled, creates URL of the form `/filename.html` instead of `/filename/`.
### watch ### watch
**Default value:** false
Watch filesystem for changes and recreate as needed. Watch filesystem for changes and recreate as needed.
{{% note %}} {{% note %}}

View file

@ -560,4 +560,4 @@ Now that you've installed Hugo, read the [Quick Start guide][quickstart] and exp
[Scoop]: https://scoop.sh/ [Scoop]: https://scoop.sh/
[snaps]: https://snapcraft.io/docs/installing-snapd [snaps]: https://snapcraft.io/docs/installing-snapd
[windowsarch]: https://esupport.trendmicro.com/en-us/home/pages/technical-support/1038680.aspx [windowsarch]: https://esupport.trendmicro.com/en-us/home/pages/technical-support/1038680.aspx
[Windows Environment Variables Editor]: http://eveditor.com/ [Windows Environment Variables Editor]: https://eveditor.com/

View file

@ -4,7 +4,6 @@ linktitle: Deployment with Rsync
description: If you have access to your web host with SSH, you can use a simple rsync one-liner to incrementally deploy your entire Hugo website. description: If you have access to your web host with SSH, you can use a simple rsync one-liner to incrementally deploy your entire Hugo website.
date: 2017-02-01 date: 2017-02-01
publishdate: 2017-02-01 publishdate: 2017-02-01
lastmod: 2019-10-03
categories: [hosting and deployment] categories: [hosting and deployment]
keywords: [rsync,deployment] keywords: [rsync,deployment]
authors: [Adrien Poupin] authors: [Adrien Poupin]
@ -139,16 +138,8 @@ sending incremental file list
index.html index.html
index.xml index.xml
sitemap.xml sitemap.xml
cours-versailles/index.html
exercices/index.html
exercices/index.xml
exercices/barycentre-et-carres-des-distances/index.html
posts/ posts/
posts/index.html posts/index.html
sujets/index.html
sujets/index.xml
sujets/2016-09_supelec-jp/index.html
tarifs-contact/index.html
sent 9,550 bytes received 1,708 bytes 7,505.33 bytes/sec sent 9,550 bytes received 1,708 bytes 7,505.33 bytes/sec
total size is 966,557 speedup is 85.86 total size is 966,557 speedup is 85.86

View file

@ -10,7 +10,7 @@ At Over we're into creativity, and technology should not get in the way. We want
People from all disciplines contribute to our website, be it legal documentation, layout and design, recruiting, marketing and of course… engineering. Hugo allows us to do this with as little friction as possible. A lot of this comes down to Hugo being distributed as a single static binary. Copy, paste, run... and you're up and running! People from all disciplines contribute to our website, be it legal documentation, layout and design, recruiting, marketing and of course… engineering. Hugo allows us to do this with as little friction as possible. A lot of this comes down to Hugo being distributed as a single static binary. Copy, paste, run... and you're up and running!
We use [Wercker](https://www.wercker.com/) for continuous integration and deployments, [GitHub](https://github.com/) for contributing to and writing markdown and [Firebase](https://firebase.google.com/docs/hosting/) for hosting. We use Wercker for continuous integration and deployments, [GitHub](https://github.com/) for contributing to and writing markdown and [Firebase](https://firebase.google.com/docs/hosting/) for hosting.
This infrastructure takes all the pressure off our engineers, anyone can contribute to our website. Anyone else can review the changes, and of course anyone with permission can deploy those approved changes as well! This infrastructure takes all the pressure off our engineers, anyone can contribute to our website. Anyone else can review the changes, and of course anyone with permission can deploy those approved changes as well!

View file

@ -162,7 +162,7 @@ The default behavior of Hugo is to pluralize list titles; hence the inflection o
### Section Template ### Section Template
This list template has been modified slightly from a template originally used in [spf13.com](http://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`. 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" >}} {{< code file="layouts/section/posts.html" >}}
{{ partial "header.html" . }} {{ partial "header.html" . }}

View file

@ -126,9 +126,9 @@ Only one `return` statement is allowed per partial file.
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. 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 ```go-html-template
Value: {{ partial "my-inline-partial" . }} Value: {{ partial "my-inline-partial.html" . }}
{{ define "partials/my-inline-partial" }} {{ define "partials/my-inline-partial.html" }}
{{ $value := 32 }} {{ $value := 32 }}
{{ return $value }} {{ return $value }}
{{ end }} {{ end }}

View file

@ -0,0 +1,172 @@
---
title: "Markdown Render Hooks"
linkTitle: "Render Hooks"
description: "Render Hooks allow custom templates to override markdown rendering functionality."
date: 2017-03-11
categories: [templates]
keywords: [markdown]
toc: true
menu:
docs:
title: "Markdown Render Hooks"
parent: "templates"
weight: 20
---
{{< new-in "0.62.0" >}} Note that this is only supported with the [Goldmark](#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" >}}
The hook kinds currently supported are:
* `image`
* `link`
* `heading` {{< new-in "0.71.0" >}}
* `codeblock`{{< new-in "0.83.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
├── render-image.html
├── render-image.rss.xml
└── render-link.html
└── render-codeblock.html
└── render-codeblock-bash.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
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.
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) {{< new-in "0.82.0" >}}
: A map of attributes (e.g. `id`, `class`)
### 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://d33wubrfki0l68.cloudfront.net/c38c7334cc3f23585738e40334284fddcaf03d5e/2e17c/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 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 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 filename and position (linenumber, column), e.g. `{{ errorf "error in code block: %s" .Position }}`.

View file

@ -61,13 +61,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: Check that you are passing variables in the `partial` function:
``` ```
{{ partial "header" }} {{ 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]. 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].
``` ```
{{ partial "header" . }} {{ partial "header.html" . }}
``` ```
The dot (`.`) is considered fundamental to understanding Hugo templating. For more information, see [Introduction to Hugo Templating][tempintro]. The dot (`.`) is considered fundamental to understanding Hugo templating. For more information, see [Introduction to Hugo Templating][tempintro].

View file

@ -26,15 +26,15 @@ toc: false
.Ordinal .Ordinal
: Zero-based ordinal in relation to its parent. If the parent is the page itself, this ordinal will represent the position of this shortcode in the page content. : Zero-based ordinal in relation to its parent. If the parent is the page itself, this ordinal will represent the position of this shortcode in the page content.
.Page
: The owning ´Page`.
.Parent .Parent
: provides access to the parent shortcode context in nested shortcodes. This can be very useful for inheritance of common shortcode parameters from the root. : provides access to the parent shortcode context in nested shortcodes. This can be very useful for inheritance of common shortcode parameters from the root.
.Position .Position
: Contains [filename and position](https://godoc.org/github.com/gohugoio/hugo/common/text#Position) for the shortcode in a page. Note that this can be relatively expensive to calculate, and is meant for error reporting. See [Error Handling in Shortcodes](/templates/shortcode-templates/#error-handling-in-shortcodes). : Contains [filename and position](https://godoc.org/github.com/gohugoio/hugo/common/text#Position) for the shortcode in a page. Note that this can be relatively expensive to calculate, and is meant for error reporting. See [Error Handling in Shortcodes](/templates/shortcode-templates/#error-handling-in-shortcodes).
.IsNamedParams .IsNamedParams
: boolean that returns `true` when the shortcode in question uses [named rather than positional parameters][shortcodes] : boolean that returns `true` when the shortcode in question uses [named rather than positional parameters][shortcodes]

View file

@ -17,9 +17,9 @@
{{ $recent := ($byLastMod | last 30).Reverse }} {{ $recent := ($byLastMod | last 30).Reverse }}
{{ $leastRecent := $byLastMod | first 10 }} {{ $leastRecent := $byLastMod | first 10 }}
<h2 id="last-updated">Last Updated</h2> <h2 id="last-updated">Last Updated</h2>
{{ partial "maintenance-pages-table" $recent }} {{ partial "maintenance-pages-table.html" $recent }}
<h2 id="least-recently-updated">Least Recently Updated</h2> <h2 id="least-recently-updated">Least Recently Updated</h2>
{{ partial "maintenance-pages-table" $leastRecent }} {{ partial "maintenance-pages-table.html" $leastRecent }}
{{/* Don't think this is possible with where directly. Should investigate. */}} {{/* Don't think this is possible with where directly. Should investigate. */}}
{{ .Scratch.Set "todos" slice }} {{ .Scratch.Set "todos" slice }}
@ -29,7 +29,7 @@
{{ end }} {{ end }}
{{ end }} {{ end }}
<h2 id="todos">Pages marked with TODO</h2> <h2 id="todos">Pages marked with TODO</h2>
{{ partial "maintenance-pages-table" (.Scratch.Get "todos") }} {{ partial "maintenance-pages-table.html" (.Scratch.Get "todos") }}
<h2 id="dependencies">Dependencies</h2> <h2 id="dependencies">Dependencies</h2>
<table class="collapse ba br2 b--black-10 pv2 ph3"> <table class="collapse ba br2 b--black-10 pv2 ph3">

View file

@ -1,27 +1,26 @@
{{ $original := .Page.Resources.GetMatch (printf "*%s*" (.Get 0)) }} {{ $img := .Page.Resources.GetMatch (printf "*%s*" (.Get 0)) }}
{{ $command := .Get 1 }} {{ $command := .Get 1 }}
{{ $options := .Get 2 }} {{ $options := .Get 2 }}
{{ if eq $command "Fit"}} {{ if eq $command "Fit"}}
{{ .Scratch.Set "image" ($original.Fit $options) }} {{ $img = $img.Fit $options }}
{{ else if eq $command "Resize"}} {{ else if eq $command "Resize"}}
{{ .Scratch.Set "image" ($original.Resize $options) }} {{ $img = $img.Resize $options }}
{{ else if eq $command "Fill"}} {{ else if eq $command "Fill"}}
{{ .Scratch.Set "image" ($original.Fill $options) }} {{ $img = $img.Fill $options }}
{{ else if eq $command "Crop"}} {{ else if eq $command "Crop"}}
{{ .Scratch.Set "image" ($original.Crop $options) }} {{ $img = $img.Crop $options }}
{{ else }} {{ else }}
{{ errorf "Invalid image processing command: Must be one of Crop, Fit, Fill or Resize."}} {{ errorf "Invalid image processing command: Must be one of Crop, Fit, Fill or Resize."}}
{{ end }} {{ end }}
{{ $image := .Scratch.Get "image" }}
<figure style="padding: 0.25rem; margin: 2rem 0; background-color: #cccc"> <figure style="padding: 0.25rem; margin: 2rem 0; background-color: #cccc">
<img style="max-width: 100%; width: auto; height: auto;" src="{{ $image.RelPermalink }}" width="{{ $image.Width }}" height="{{ $image.Height }}"> <img style="max-width: 100%; width: auto; height: auto;" src="{{ $img.RelPermalink }}" width="{{ $img.Width }}" height="{{ $img.Height }}">
<figcaption> <figcaption>
<small> <small>
{{ with .Inner }} {{ with .Inner }}
{{ . }} {{ . }}
{{ else }} {{ else }}
.{{ $command }} "{{ $options }}" .{{ $command }} "{{ $options }}"
{{ end }} {{ end }}
</small> </small>
</figcaption> </figcaption>
</figure> </figure>

View file

@ -3,7 +3,7 @@ publish = "public"
command = "hugo --gc --minify" command = "hugo --gc --minify"
[context.production.environment] [context.production.environment]
HUGO_VERSION = "0.93.3" HUGO_VERSION = "0.95.0"
HUGO_ENV = "production" HUGO_ENV = "production"
HUGO_ENABLEGITINFO = "true" HUGO_ENABLEGITINFO = "true"
@ -11,20 +11,20 @@ HUGO_ENABLEGITINFO = "true"
command = "hugo --gc --minify --enableGitInfo" command = "hugo --gc --minify --enableGitInfo"
[context.split1.environment] [context.split1.environment]
HUGO_VERSION = "0.93.3" HUGO_VERSION = "0.95.0"
HUGO_ENV = "production" HUGO_ENV = "production"
[context.deploy-preview] [context.deploy-preview]
command = "hugo --gc --minify --buildFuture -b $DEPLOY_PRIME_URL" command = "hugo --gc --minify --buildFuture -b $DEPLOY_PRIME_URL"
[context.deploy-preview.environment] [context.deploy-preview.environment]
HUGO_VERSION = "0.93.3" HUGO_VERSION = "0.95.0"
[context.branch-deploy] [context.branch-deploy]
command = "hugo --gc --minify -b $DEPLOY_PRIME_URL" command = "hugo --gc --minify -b $DEPLOY_PRIME_URL"
[context.branch-deploy.environment] [context.branch-deploy.environment]
HUGO_VERSION = "0.93.3" HUGO_VERSION = "0.95.0"
[context.next.environment] [context.next.environment]
HUGO_ENABLEGITINFO = "true" HUGO_ENABLEGITINFO = "true"