Compare commits

..

19 Commits

Author SHA1 Message Date
hugoreleaser fe7e137e28 releaser: Prepare repository for 0.135.0-DEV
[ci skip]
2024-09-10 11:00:15 +00:00
hugoreleaser 1c74abd260 releaser: Bump versions for release of 0.134.2
[ci skip]
2024-09-10 10:46:33 +00:00
Bjørn Erik Pedersen 3d6baedaec Don't count HTML markup in auto summaries
This commit also fixes a bug where a `</picture>` end tag was wrongly used to detect a end paragraph. This should be very rare, though.

Closes #12837
2024-09-10 11:03:47 +02:00
hugoreleaser 84ee00bbc2 releaser: Prepare repository for 0.135.0-DEV
[ci skip]
2024-09-05 10:32:40 +00:00
hugoreleaser 2f89169baa releaser: Bump versions for release of 0.134.1
[ci skip]
2024-09-05 10:17:50 +00:00
Bjørn Erik Pedersen 66a3a11001 Fix stray end p tag in Obsidian callout titles
Also remove test references to deprecated funcs now in ERROR.

Closes #12828
2024-09-05 12:12:24 +02:00
Bjørn Erik Pedersen 8f2eac0195 Make ContentWithoutSummary return Content when summary is fetched from front matter
Fixes #12822
2024-09-05 12:12:24 +02:00
Bjørn Erik Pedersen b570a5f118 Merge commit '39fd3b557014e339bc6c68a7ff34a7734a735ee0' 2024-09-04 18:57:34 +02:00
Bjørn Erik Pedersen 39fd3b5570 Squashed 'docs/' changes from a49697e53..ccb1b97cb
ccb1b97cb Update blockquotes.md
a5f51431c Add new-in label
39dac5838 Document ContentWithoutSummary
de3c75694 Clarify blockquote render hook Markdown syntax
d32f7856d Document change to data type returned by render hook Text methods
83fe7ccc3 Document table render hooks
601234147 netlify: Hugo 0.134.0
a583640a0 Add support for Obsidian type blockquote alerts
3e0080861 Merge commit 'dec8cd4ada29218971743333f8ac662a9c06aad8'
2dde06576 output: Fix docshelper template lookup order for AMP pages

git-subtree-dir: docs
git-subtree-split: ccb1b97cbb
2024-09-04 18:52:05 +02:00
hugoreleaser aacff7aff4 releaser: Prepare repository for 0.135.0-DEV
[ci skip]
2024-09-03 10:14:44 +00:00
hugoreleaser 77df7bbbff releaser: Bump versions for release of 0.134.0
[ci skip]
2024-09-03 09:54:22 +00:00
Aymen Rachdi ae3815898f Update Dockerfile 2024-09-02 21:56:33 +02:00
Bjørn Erik Pedersen 504a23184f markup/goldmark/blockquotes: Improve some tests 2024-09-01 18:25:10 +02:00
Bjørn Erik Pedersen e651d29801 Add support for Obsidian type blockquote alerts
* Make the alert type parsing more flexible to support more types
* Add `AlertTitle` and `AlertSign` (for folding)

Note that GitHub will not render callouts with alert title/sign.

See https://help.obsidian.md/Editing+and+formatting/Callouts

Closes #12805
Closes #12801
2024-09-01 18:12:26 +02:00
Bjørn Erik Pedersen dec8cd4ada Squashed 'docs/' changes from fcc3ed651..a49697e53
a49697e53 Add private use subtag requirements to multilingual page
a5c6bb4da Add INFINI Pizza search engine
45b732efa Fix template lookup order for AMP pages
30c672d0b netlify: Hugo 0.133.1
7c766e724 Update page resources documentation
ca802fbec Document how to enable AsciiDoc syntax highlighting
c3350f4cf Update definition of falsy to include zero time.Time values
b0e5ab051 Fir typo
60f6cb63b Update migrations.md
ec52c7ba1 Improve formatting of example code
e5681ad01 Improve formatting of example code
bdf3ffc73 Clarify the various next/prev methods
b5505d22a Clarify template lookup order for shortcodes
cf8dd7034 Improve embedded.md
e5dee2651 Update transform.ToMath
4d419a128 Update pagination configuration to use new struct
05d4fd597 Update PrevInSection.md
fd33370ed Add new-in 0.133.0
f9062042f Add the new page config section
205645e97 Remove out-dated  new-in
3ed3673f7 Fix typo
41df91659 Document the 'else with' construct introduced with Go 1.23
9c4697ab3 netlify: Hugo 0.133.0
62506b052 Merge branch 'temp133'
877e1bfcd Add config options page.nextPrevSortOrder/nextPrevInSectionSortOrder
eb159fe62 Update menu.md
efa7795a0 Update theme
dbe8911ad netlify: Hugo 0.132.2
2f793d328 Document passthrough render hooks
a7ce9a5e8 netlify: Hugo 0.132.1
2c137cb48 Update blockquotes.md
e0fa2f0d1 Add new-in badge to blockquote render hook page
bf42bbe6b Update references to render hooks
85a3d9958 Update theme
2dae72128 Document blockquote render hooks
8f5afb55d Update plainify return type
160f22d0e netlify: Hugo 0.132.0
82b5586fb Document transform.ToMath
1efcbcddb tpl/transform: Make Plainify and ToMath return template.HTML
31727be2e docs: Regen docshelper
88a421426 Merge commit 'a6e635ca7d905d9ec3ffd708db2694f680b03aae'

git-subtree-dir: docs
git-subtree-split: a49697e536
2024-09-01 14:51:15 +02:00
Bjørn Erik Pedersen 0c453420e6 Merge commit 'dec8cd4ada29218971743333f8ac662a9c06aad8' 2024-09-01 14:51:15 +02:00
Bjørn Erik Pedersen 469124823c Rename hstring.RenderedHTML => hstring.HTML
And add a comment about why it exists.
2024-09-01 10:04:20 +02:00
Bjørn Erik Pedersen 96afea4acc github: Try to fix "no space left on device" on MacOS 2024-08-31 21:05:58 +02:00
Bjørn Erik Pedersen 6d97ee711e Make all renderhook Text methods return template.HTML 2024-08-31 21:05:58 +02:00
70 changed files with 1358 additions and 563 deletions
+1 -1
View File
@@ -2,7 +2,7 @@
# Twitter: https://twitter.com/gohugoio
# Website: https://gohugo.io/
FROM golang:1.21-alpine AS build
FROM golang:1.22.6-alpine AS build
# Optionally set HUGO_BUILD_TAGS to "extended" or "nodeploy" when building like so:
# docker build --build-arg HUGO_BUILD_TAGS=extended .
+1 -1
View File
@@ -17,7 +17,7 @@ package hugo
// This should be the only one.
var CurrentVersion = Version{
Major: 0,
Minor: 134,
Minor: 135,
PatchLevel: 0,
Suffix: "-DEV",
}
+8 -6
View File
@@ -19,16 +19,18 @@ import (
"github.com/gohugoio/hugo/common/types"
)
var _ types.PrintableValueProvider = RenderedHTML("")
var _ types.PrintableValueProvider = HTML("")
// RenderedHTML is a string that represents rendered HTML.
// When printed in templates it will be rendered as template.HTML and considered safe.
type RenderedHTML string
// HTML is a string that represents rendered HTML.
// When printed in templates it will be rendered as template.HTML and considered safe so no need to pipe it into `safeHTML`.
// This type was introduced as a wasy to prevent a common case of inifinite recursion in the template rendering
// when the `linkify` option is enabled with a common (wrong) construct like `{{ .Text | .Page.RenderString }}` in a hook template.
type HTML string
func (s RenderedHTML) String() string {
func (s HTML) String() string {
return string(s)
}
func (s RenderedHTML) PrintableValue() any {
func (s HTML) PrintableValue() any {
return template.HTML(s)
}
+2 -2
View File
@@ -25,6 +25,6 @@ func TestRenderedString(t *testing.T) {
c := qt.New(t)
// Validate that it will behave like a string in Hugo settings.
c.Assert(cast.ToString(RenderedHTML("Hugo")), qt.Equals, "Hugo")
c.Assert(template.HTML(RenderedHTML("Hugo")), qt.Equals, template.HTML("Hugo"))
c.Assert(cast.ToString(HTML("Hugo")), qt.Equals, "Hugo")
c.Assert(template.HTML(HTML("Hugo")), qt.Equals, template.HTML("Hugo"))
}
@@ -1,4 +1,4 @@
{{ define "main" }}
{{ $section_to_display := (.Site.Taxonomies.categories.fundamentals).Pages | lang.Merge (.Sites.First.Taxonomies.categories.fundamentals).Pages }}
{{ $section_to_display := (.Site.Taxonomies.categories.fundamentals).Pages | lang.Merge (.Sites.Default.Taxonomies.categories.fundamentals).Pages }}
{{ partial "pagelayout.html" (dict "context" . "section_to_display" $section_to_display ) }}
{{ end }}
@@ -1,5 +1,5 @@
{{ define "main" }}
{{ $paginator := .Paginate (.Pages | lang.Merge (where .Sites.First.RegularPages "Section" .Section)) }}
{{ $paginator := .Paginate (.Pages | lang.Merge (where .Sites.Default.RegularPages "Section" .Section)) }}
{{ $section_to_display := .Sections | default $paginator.Pages }}
{{ partial "pagelayout.html" (dict "context" . "section_to_display" $section_to_display ) }}
{{ end }}
@@ -1,5 +1,6 @@
{{ $text := `
Most of the commands for **Hugo Modules** require a newer version of Go installed (see https://golang.org/dl/) and the relevant VCS client (e.g. Git, see https://git-scm.com/downloads/ ). If you have an "older" site running on Netlify, you may have to set GO_VERSION to 1.12 in your Environment settings.
Most of the commands for **Hugo Modules** require a newer version (>= 1.18) of Go installed (see https://golang.org/dl/) and the relevant VCS client (e.g. Git, see https://git-scm.com/downloads/ ).
If you have an "older" site running on Netlify, you may have to set GO_VERSION to 1.19 or newer in your Environment settings.
For more information about Go Modules, see:
+1 -1
View File
@@ -1 +1 @@
# github.com/gohugoio/gohugoioTheme v0.0.0-20240728210410-d42c342ce472
# github.com/gohugoio/gohugoioTheme v0.0.0-20240815082608-66ccd383a90f
+1 -1
View File
@@ -49,7 +49,7 @@ toc: true
: Leverage the embedded Markdown extensions to create tables, definition lists, footnotes, task lists, inserted text, mark text, subscripts, superscripts, and more.
[Markdown render hooks]
: Override the conversion of Markdown to HTML when rendering fenced code blocks, headings, images, and links. For example, render every standalone image as an HTML `figure` element.
: Override the conversion of Markdown to HTML when rendering blockquotes, fenced code blocks, headings, images, links, and tables. For example, render every standalone image as an HTML `figure` element.
[Diagrams]
: Use fenced code blocks and Markdown render hooks to include diagrams in your content.
@@ -125,7 +125,7 @@ Set any [front matter field] in the map passed to the [`AddPage`](#addpage) meth
This table describes the fields most commonly passed to the `AddPage` method.
Key|Descripion|Required
Key|Description|Required
:--|:--|:-:
`content.mediaType`|The content [media type]. Default is `text/markdown`. See [content formats] for examples.|&nbsp;
`content.value`|The content value as a string.|&nbsp;
@@ -148,7 +148,7 @@ When setting the `path`, Hugo transforms the given string to a logical path. For
Construct the map passed to the [`AddResource`](#addresource) method using the fields below.
Key|Descripion|Required
Key|Description|Required
:--|:--|:-:
`content.mediaType`|The content [media type].|:heavy_check_mark:
`content.value`|The content value as a string or resource.|:heavy_check_mark:
@@ -21,15 +21,22 @@ This is the default language configuration:
In the above, `en` is the language key.
{{% note %}}
Each language key must conform to the syntax described in [RFC 5646]. You must use hyphens to separate subtags. For example:
Language keys must conform to the syntax described in [RFC 5646]. For example:
- `en`
- `en-GB`
- `pt-BR`
- `en-US`
Artificial languages with private use subtags as defined in [RFC 5646 § 2.2.7] are also supported. Omit the `art-x-` prefix from the language key. For example:
- `hugolang`
{{% note %}}
Private use subtags must not exceed 8 alphanumeric characters.
{{% /note %}}
[RFC 5646]: https://datatracker.ietf.org/doc/html/rfc5646#section-2.1
{{% /note %}}
[RFC 5646 § 2.2.7]: https://datatracker.ietf.org/doc/html/rfc5646#section-2.2.7
This is an example of a site configuration for a multilingual project. Any key not defined in a `languages` object will fall back to the global value in the root of your site configuration.
@@ -1,6 +1,6 @@
---
title: Page resources
description: Page resources -- images, other pages, documents, etc. -- have page-relative URLs and their own metadata.
description: Use page resources to logically associate assets with a page.
categories: [content management]
keywords: [bundle,content,resources]
menu:
@@ -37,82 +37,83 @@ content
└── index.md (root of page bundle)
```
## Properties
## Examples
ResourceType
: The main type of the resource's [Media Type](/templates/output-formats/#media-types). For example, a file of MIME type `image/jpeg` has the ResourceType `image`. A `Page` will have `ResourceType` with value `page`.
Use any of these methods on a `Page` object to capture page resources:
Name
: Default value is the file name (relative to the owning page). Can be set in front matter.
- [`Resources.ByType`]
- [`Resources.Get`]
- [`Resources.GetMatch`]
- [`Resources.Match`]
Title
: Default value is the same as `.Name`. Can be set in front matter.
Once you have captured a resource, use any of the applicable [`Resource`] methods to return a value or perform an action.
Permalink
: The absolute URL to the resource. Resources of type `page` will have no value.
[`Resource`]: /methods/resource
[`Resources.ByType`]: /methods/page/resources#bytype
[`Resources.GetMatch`]: /methods/page/resources#getmatch
[`Resources.Get`]: /methods/page/resources#get
[`Resources.Match`]: /methods/page/resources#match
RelPermalink
: The relative URL to the resource. Resources of type `page` will have no value.
The following examples assume this content structure:
Content
: The content of the resource itself. For most resources, this returns a string
with the contents of the file. Use this to create inline resources.
```text
content/
└── example/
├── data/
│ └── books.json <-- page resource
├── images/
│ ├── a.jpg <-- page resource
│ └── b.jpg <-- page resource
├── snippets/
│ └── text.md <-- page resource
└── index.md
```
Render a single image, and throw an error if the file does not exist:
```go-html-template
{{ with .Resources.GetMatch "script.js" }}
<script>{{ .Content | safeJS }}</script>
{{ end }}
{{ with .Resources.GetMatch "style.css" }}
<style>{{ .Content | safeCSS }}</style>
{{ end }}
{{ with .Resources.GetMatch "img.png" }}
<img src="data:{{ .MediaType.Type }};base64,{{ .Content | base64Encode }}">
{{ $path := "images/a.jpg" }}
{{ with .Resources.Get $path }}
<img src="{{ .RelPermalink }}" width="{{ .Width }}" height="{{ .Height }}" alt="">
{{ else }}
{{ errorf "Unable to get page resource %q" $path }}
{{ end }}
```
MediaType.Type
: The media type (formerly known as a MIME type) of the resource (e.g., `image/jpeg`).
MediaType.MainType
: The main type of the resource's media type (e.g., `image`).
MediaType.SubType
: The subtype of the resource's type (e.g., `jpeg`). This may or may not correspond to the file suffix.
MediaType.Suffixes
: A slice of possible file suffixes for the resource's media type (e.g., `[jpg jpeg jpe jif jfif]`).
## Methods
ByType
: Returns the page resources of the given type.
Render all images, resized to 300 px wide:
```go-html-template
{{ .Resources.ByType "image" }}
{{ range .Resources.ByType "image" }}
{{ with .Resize "300x" }}
<img src="{{ .RelPermalink }}" width="{{ .Width }}" height="{{ .Height }}" alt="">
{{ end }}
{{ end }}
```
Match
: Returns all the page resources (as a slice) whose `Name` matches the given Glob pattern ([examples](https://github.com/gobwas/glob/blob/master/readme.md)). The matching is case-insensitive.
Render the markdown snippet:
```go-html-template
{{ .Resources.Match "images/*" }}
{{ with .Resources.Get "snippets/text.md" }}
{{ .Content }}
{{ end }}
```
GetMatch
: Same as `Match` but will return the first match.
List the titles in the data file, and throw an error if the file does not exist.
### Pattern matching
```go
// Using Match/GetMatch to find this images/sunset.jpg ?
.Resources.Match "images/sun*" ✅
.Resources.Match "**/sunset.jpg" ✅
.Resources.Match "images/*.jpg" ✅
.Resources.Match "**.jpg" ✅
.Resources.Match "*" 🚫
.Resources.Match "sunset.jpg" 🚫
.Resources.Match "*sunset.jpg" 🚫
```go-html-template
{{ $path := "data/books.json" }}
{{ with .Resources.Get $path }}
{{ with . | transform.Unmarshal }}
<p>Books:</p>
<ul>
{{ range . }}
<li>{{ .title }}</li>
{{ end }}
</ul>
{{ end }}
{{ else }}
{{ errorf "Unable to get page resource %q" $path }}
{{ end }}
```
## Metadata
@@ -124,21 +125,21 @@ Resources of type `page` get `Title` etc. from their own front matter.
{{% /note %}}
name
: Sets the value returned in `Name`.
: (`string`) Sets the value returned in `Name`.
{{% note %}}
The methods `Match`, `Get` and `GetMatch` use `Name` to match the resources.
{{% /note %}}
title
: Sets the value returned in `Title`
: (`string`) Sets the value returned in `Title`
params
: A map of custom key-value pairs.
: (`map`) A map of custom key-value pairs.
### Resources metadata example
{{< code-toggle >}}
{{< code-toggle file=content/example.md fm=true >}}
title: Application
date : 2018-01-25
resources :
@@ -173,7 +174,7 @@ From the example above:
- Every docx in the bundle will receive the `word` icon.
{{% note %}}
The __order matters__ --- Only the **first set** values of the `title`, `name` and `params`-**keys** will be used. Consecutive parameters will be set only for the ones not already set. In the above example, `.Params.icon` is first set to `"photo"` in `src = "documents/photo_specs.pdf"`. So that would not get overridden to `"pdf"` by the later set `src = "**.pdf"` rule.
The order matters; only the first set values of the `title`, `name` and `params` keys will be used. Consecutive parameters will be set only for the ones not already set. In the above example, `.Params.icon` is first set to `"photo"` in `src = "documents/photo_specs.pdf"`. So that would not get overridden to `"pdf"` by the later set `src = "**.pdf"` rule.
{{% /note %}}
### The `:counter` placeholder in `name` and `title`
@@ -92,11 +92,11 @@ Note that the `summaryLength` is an approximate number of words.
Each summary type has different characteristics:
Type|Precedence|Renders markdown|Renders shortcodes|Strips HTML tags|Wraps single lines with `<p>`
:--|:-:|:-:|:-:|:-:|:-:
Manual|1|:heavy_check_mark:|:heavy_check_mark:|:x:|:heavy_check_mark:
Front&nbsp;matter|2|:heavy_check_mark:|:x:|:x:|:x:
Automatic|3|:heavy_check_mark:|:heavy_check_mark:|:heavy_check_mark:|:x:
Type|Precedence|Renders markdown|Renders shortcodes|Wraps single lines with `<p>`
:--|:-:|:-:|:-:|:-:
Manual|1|:heavy_check_mark:|:heavy_check_mark:|:heavy_check_mark:
Front&nbsp;matter|2|:heavy_check_mark:|:x:|:x:
Automatic|3|:heavy_check_mark:|:heavy_check_mark:|:heavy_check_mark:
## Rendering
+1 -1
View File
@@ -48,7 +48,7 @@ For a complete guide to contributing to Hugo, see the [Contribution Guide].
To build the extended edition of Hugo from source you must:
1. Install [Git]
1. Install [Go] version 1.20 or later
1. Install [Go] version 1.23.0 or later
1. Install a C compiler, either [GCC] or [Clang]
1. Update your `PATH` environment variable as described in the [Go documentation]
@@ -2,4 +2,6 @@
# Do not remove front matter.
---
In Go templates, the falsy values are `false`, `0`, any nil pointer or interface value, and any array, slice, map, or string of length zero. Everything else is truthy.
The falsy values are `false`, `0`, any `nil` pointer or interface value, any array, slice, map, or string of length zero, and zero `time.Time` values.
Everything else is truthy.
+1 -1
View File
@@ -34,7 +34,7 @@ Use with the [`else`] statement:
{{ end }}
```
Use `else if` to check multiple conditions.
Use `else if` to check multiple conditions:
```go-html-template
{{ $var := 12 }}
@@ -36,6 +36,20 @@ Use with the [`else`] statement:
{{ end }}
```
Use `else with` to check multiple conditions:
```go-html-template
{{ $v1 := 0 }}
{{ $v2 := 42 }}
{{ with $v1 }}
{{ . }}
{{ else with $v2 }}
{{ . }} → 42
{{ else }}
{{ print "v1 and v2 are falsy" }}
{{ end }}
```
Initialize a variable, scoped to the current block:
```go-html-template
@@ -0,0 +1,112 @@
---
title: transform.ToMath
description: Renders a math expression using KaTeX.
categories: []
keywords: []
action:
aliases: []
related:
- content-management/mathematics
returnType: types.Result[template.HTML]
signatures: ['transform.ToMath EXPRESSION [OPTIONS]']
aliases: [/functions/tomath]
toc: true
---
{{< new-in "0.132.0" >}}
{{% note %}}
This feature was introduced in Hugo 0.132.0 and is marked as experimental.
This does not mean that it's going to be removed, but this is our first use of WASI/Wasm in Hugo, and we need to see how it [works in the wild](https://github.com/gohugoio/hugo/issues/12736) before we can set it in stone.
{{% /note %}}
## Arguments
EXPRESSION
: The math expression to render using KaTeX.
OPTIONS
: A map of zero or more options.
## Options
These are a subset of the [KaTeX options].
output
: (`string`). Determines the markup language of the output. One of `html`, `mathml`, or `htmlAndMathml`. Default is `mathml`.
<!-- Indent to prevent spliting the description list. -->
With `html` and `htmlAndMathml` you must include KaTeX CSS within the `head` element of your base template. For example:
```html
<head>
...
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/katex@0.16.11/dist/katex.min.css" integrity="sha384-nB0miv6/jRmo5UMMR1wu3Gz6NLsoTkbqJghGIsx//Rlm+ZU03BU6SQNC66uf4l5+" crossorigin="anonymous">
...
</head>
```
displayMode
: (`bool`) If `true` render in display mode, else render in inline mode. Default is `false`.
leqno
: (`bool`) If `true` render with the equation numbers on the left. Default is `false`.
fleqn
: (`bool`) If `true` render flush left with a 2em left margin. Default is `false`.
minRuleThickness
: (`float`) The minimum thickness of the fraction lines in `em`. Default is `0.04`.
macros
: (`map`) A map of macros to be used in the math expression. Default is `{}`.
throwOnError
: (`bool`) If `true` throw a `ParseError` when KaTeX encounters an unsupported command or invalid LaTex. See [error handling]. Default is `true`.
errorColor
: (`string`) The color of the error messages expressed as an RGB [hexadecimal color]. Default is `#cc0000`.
## Examples
### Basic
```go-html-template
{{ transform.ToMath "c = \\pm\\sqrt{a^2 + b^2}" }}
```
### Macros
```go-html-template
{{ $macros := dict
"\\addBar" "\\bar{#1}"
"\\bold" "\\mathbf{#1}"
}}
{{ $opts := dict "macros" $macros }}
{{ transform.ToMath "\\addBar{y} + \\bold{H}" $opts }}
```
## Error handling
There are 3 ways to handle errors from KaTeX:
1. Let KaTeX throw an error and make the build fail. This is the default behavior.
1. Handle the error in your template. See the render hook example below.
1. Set the `throwOnError` option to `false` to make KaTeX render the expression as an error instead of throwing an error. See [options].
{{< code file=layouts/_default/_markup/render-passthrough-inline.html copy=true >}}
{{ with transform.ToMath .Inner }}
{{ with .Err }}
{{ errorf "Failed to render KaTeX: %q. See %s" . $.Position }}
{{ else }}
{{ . }}
{{ end }}
{{ end }}
{{- /* chomp trailing newline */ -}}
{{< /code >}}
[error handling]: #error-handling
[KaTeX options]: https://katex.org/docs/options.html
[hexadecimal color]: https://developer.mozilla.org/en-US/docs/Web/CSS/hex-color
@@ -238,7 +238,7 @@ This is the default configuration for the AsciiDoc renderer:
###### attributes
(`map`) A map of key-value pairs, each a document attributes,See Asciidoctors [attributes].
(`map`) A map of key-value pairs, each a document attributes. See Asciidoctors [attributes].
[attributes]: https://asciidoctor.org/docs/asciidoc-syntax-quick-reference/#attributes-and-substitutions
@@ -302,6 +302,51 @@ To mitigate security risks, entries in the extension array may not contain forwa
my-attribute-name = "my value"
{{< /code-toggle >}}
### AsciiDoc syntax highlighting
Follow the steps below to enable syntax highlighting.
Step 1
: Set the `source-highlighter` attribute in your site configuration. For example:
{{< code-toggle file=hugo >}}
[markup.asciidocExt.attributes]
source-highlighter = 'rouge'
{{< /code-toggle >}}
Step 2
: Generate the highlighter CSS. For example:
```text
rougify style monokai.sublime > assets/css/syntax.css
```
Step 3
: In your base template add a link to the CSS file:
{{< code file=layouts/_default/baseof.html >}}
<head>
...
{{ with resources.Get "css/syntax.css" }}
<link rel="stylesheet" href="{{ .RelPermalink }}" integrity="{{ .Data.Integrity }}" crossorigin="anonymous">
{{ end }}
...
</head>
{{< /code >}}
Then add the code to be highlighted to your markup:
```text
[#hello,ruby]
----
require 'sinatra'
get '/hi' do
"Hello World!"
end
----
```
### AsciiDoc troubleshooting
Run `hugo --logLevel debug` to examine Hugo's call to the Asciidoctor executable:
@@ -378,6 +378,10 @@ Module configuration see [module configuration](/hugo-modules/configuration/).
See [custom output formats].
###### page
See [configure page](#configure-page).
###### pagination
See [configure pagination](/templates/pagination/#configuration).
@@ -496,6 +500,50 @@ enableemoji: true
```
{{% /note %}}
## Configure page
{{< new-in 0.133.0 >}}
These methods on a `Page` object navigate to the next or previous page within a page collection, relative to the current page:
- [Next](/methods/page/next/)
- [NextInSection](/methods/page/nextinsection/)
- [Prev](/methods/page/prev/)
- [PrevInSection](/methods/page/previnsection/)
Hugo determines the _next_ and _previous_ page by sorting a page collection according to this sorting hierarchy:
Field|Precedence|Sort direction
:--|:--|:--
[`weight`]|1|descending
[`date`]|2|descending
[`linkTitle`]|3|descending
[`path`]|4|descending
[`date`]: /methods/page/date/
[`weight`]: /methods/page/weight/
[`linkTitle`]: /methods/page/linktitle/
[`path`]: /methods/page/path/
The sort direction in the table above corresponds to these default site configuration values:
{{< code-toggle config=page />}}
To sort all fields in ascending order:
{{< code-toggle file=hugo >}}
[page]
nextPrevInSectionSortOrder = 'asc'
nextPrevSortOrder = 'asc'
{{< /code-toggle >}}
{{% note %}}
These settings do not apply to the [`Next`] or [`Prev`] methods on a `Pages` object.
[`Next`]: /methods/pages/next
[`Prev`]: /methods/pages/next
{{% /note %}}
## Configure build
The `build` configuration section contains global build-related configuration options.
@@ -609,8 +657,6 @@ Setting `force=true` will make a redirect even if there is existing content in t
## 404 server error page {#_404-server-error-page}
{{< new-in 0.103.0 >}}
Hugo will, by default, render all 404 errors when running `hugo server` with the `404.html` template. Note that if you have already added one or more redirects to your [server configuration](#configure-server), you need to add the 404 redirect explicitly, e.g:
{{< code-toggle file=config/development/server >}}
@@ -924,7 +970,6 @@ output
It is recommended to put coarse grained filters (e.g. for language and output format) in the excludes section, e.g.:
{{< code-toggle file=hugo >}}
[segments.segment1]
[[segments.segment1.excludes]]
-13
View File
@@ -1,13 +0,0 @@
---
cascade:
_build:
list: never
publishResources: false
render: never
---
<!--
Files within this headless branch bundle are Markdown snippets. Each file must contain front matter delimiters, though front matter fields are not required.
Include the rendered content using the "include" shortcode.
-->
@@ -1,37 +0,0 @@
---
# Do not remove front matter.
---
The `Next` and `Prev` methods on a `Pages` object are more flexible than the `Next` and `Prev` methods on a `Page` object.
||Page collection|Custom sort order
:--|:--|:-:
[`PAGES.Next`] and [`PAGES.Prev`]|locally defined|✔️
[`PAGE.Next`] and [`PAGE.Prev`]|globally defined|❌
[`PAGES.Next`]: /methods/pages/next/
[`PAGES.Prev`]: /methods/pages/prev/
[`PAGE.Next`]: /methods/page/next/
[`PAGE.Prev`]: /methods/page/prev/
locally defined
: Build the page collection every time you call `PAGES.Next` and `PAGES.Prev`. Navigation between pages is relative to the current page's position within the local collection, independent of the global collection.
With a local collection, the navigation sort order is the same as the collection sort order.
globally defined
: Build the page collection once, on a list page. Navigation between pages is relative to the current page's position within the global collection.
With a global collection, the navigation sort order is fixed, using Hugo's default sort order. In order of precedence:
1. Page [weight]
2. Page [date] (descending)
3. Page [linkTitle], falling back to page [title]
4. Page file path if the page is backed by a file
For example, with a global collection sorted by title, the navigation sort order will use Hugo's default sort order. This is probably not what you want or expect. For this reason, the `Next` and `Prev` methods on a `Pages` object are generally a better choice.
[date]: /methods/page/date/
[weight]: /methods/page/weight/
[linkTitle]: /methods/page/linktitle/
[title]: /methods/page/title/
+3 -3
View File
@@ -5,6 +5,8 @@ categories: []
keywords: []
action:
related:
- methods/page/Summary
- methods/page/ContentWithoutSummary
- methods/page/RawContent
- methods/page/Plain
- methods/page/PlainWords
@@ -13,9 +15,7 @@ action:
signatures: [PAGE.Content]
---
The `Content` method on a `Page` object renders Markdown and shortcodes to HTML. The content does not include front matter.
[shortcodes]: /getting-started/glossary/#shortcode
The `Content` method on a `Page` object renders Markdown and shortcodes to HTML.
```go-html-template
{{ .Content }}
@@ -0,0 +1,28 @@
---
title: ContentWithoutSummary
description: Returns the rendered content of the given page, excluding the content summary.
categories: []
keywords: []
action:
related:
- methods/page/Content
- methods/page/Summary
- methods/page/RawContent
- methods/page/Plain
- methods/page/PlainWords
- methods/page/RenderShortcodes
returnType: template.HTML
signatures: [PAGE.ContentWithoutSummary]
---
{{< new-in 0.134.0 >}}
Applicable when using manual or automatic [content summaries], the `ContentWithoutSummary` method on a `Page` object renders Markdown and shortcodes to HTML, excluding the content summary from the result.
[content summaries]: /content-management/summaries/#manual-summary
```go-html-template
{{ .ContentWithoutSummary }}
```
The `ContentWithoutSummary` method returns an empty string if you define the content summary in front matter.
+2 -38
View File
@@ -1,6 +1,6 @@
---
title: Next
description: Returns the next page in a global page collection, relative to the given page.
description: Returns the next page in a site's collection of regular pages, relative to the current page.
categories: []
keywords: []
action:
@@ -12,42 +12,6 @@ action:
- methods/pages/Prev
returnType: page.Page
signatures: [PAGE.Next]
toc: true
---
The behavior of the `Prev` and `Next` methods on a `Page` object is probably the reverse of what you expect.
With this content structure:
```text
content/
├── pages/
│ ├── _index.md
│ ├── page-1.md <-- front matter: weight = 10
│ ├── page-2.md <-- front matter: weight = 20
│ └── page-3.md <-- front matter: weight = 30
└── _index.md
```
When you visit page-2:
- The `Prev` method points to page-3
- The `Next` method points to page-1
{{% note %}}
Use the opposite label in your navigation links as shown in the example below.
{{% /note %}}
```go-html-template
{{ with .Next }}
<a href="{{ .RelPermalink }}">Prev</a>
{{ end }}
{{ with .Prev }}
<a href="{{ .RelPermalink }}">Next</a>
{{ end }}
```
## Compare to Pages methods
{{% include "methods/_common/next-prev-on-page-vs-next-prev-on-pages.md" %}}
{{% include "methods/page/_common/next-and-prev.md" %}}
+2 -58
View File
@@ -1,71 +1,15 @@
---
title: NextInSection
description: Returns the next page within a section, relative to the given page.
description: Returns the next regular page in a section, relative to the given page.
categories: []
keywords: []
action:
related:
- methods/page/PrevInSection
- methods/page/Next
- methods/page/Prev
- methods/pages/Next
- methods/pages/Prev
returnType: page.Page
signatures: [PAGE.NextInSection]
---
The behavior of the `PrevInSection` and `NextInSection` methods on a `Page` object is probably the reverse of what you expect.
With this content structure:
```text
content/
├── books/
│ ├── _index.md
│ ├── book-1.md
│ ├── book-2.md
│ └── book-3.md
├── films/
│ ├── _index.md
│ ├── film-1.md
│ ├── film-2.md
│ └── film-3.md
└── _index.md
```
When you visit book-2:
- The `PrevInSection` method points to book-3
- The `NextInSection` method points to book-1
{{% note %}}
Use the opposite label in your navigation links as shown in the example below.
{{% /note %}}
```go-html-template
{{ with .NextInSection }}
<a href="{{ .RelPermalink }}">Previous in section</a>
{{ end }}
{{ with .PrevInSection }}
<a href="{{ .RelPermalink }}">Next in section</a>
{{ end }}
```
{{% note %}}
The navigation sort order may be different than the page collection sort order.
{{% /note %}}
With the `PrevInSection` and `NextInSection` methods, the navigation sort order is fixed, using Hugos default sort order. In order of precedence:
1. Page [weight]
2. Page [date] (descending)
3. Page [linkTitle], falling back to page [title]
4. Page file path if the page is backed by a file
For example, with a page collection sorted by title, the navigation sort order will use Hugos default sort order. This is probably not what you want or expect. For this reason, the Next and Prev methods on a Pages object are generally a better choice.
[date]: /methods/page/date/
[weight]: /methods/page/weight/
[linkTitle]: /methods/page/linktitle/
[title]: /methods/page/title/
{{% include "methods/page/_common/nextinsection-and-previnsection.md" %}}
+3 -1
View File
@@ -6,6 +6,8 @@ keywords: []
action:
related:
- methods/page/Content
- methods/page/Summary
- methods/page/ContentWithoutSummary
- methods/page/RawContent
- methods/page/PlainWords
- methods/page/RenderShortcodes
@@ -13,7 +15,7 @@ action:
signatures: [PAGE.Plain]
---
The `Plain` method on a `Page` object renders Markdown and [shortcodes] to HTML, then strips the HTML [tags]. It does not strip HTML [entities]. The plain content does not include front matter.
The `Plain` method on a `Page` object renders Markdown and [shortcodes] to HTML, then strips the HTML [tags]. It does not strip HTML [entities].
To prevent Go's [html/template] package from escaping HTML entities, pass the result through the [`htmlUnescape`] function.
@@ -6,8 +6,11 @@ keywords: []
action:
related:
- methods/page/Content
- methods/page/Summary
- methods/page/ContentWithoutSummary
- methods/page/RawContent
- methods/page/Plain
- methods/page/RenderShortcodes
returnType: '[]string'
signatures: [PAGE.PlainWords]
---
+4 -40
View File
@@ -1,53 +1,17 @@
---
title: Prev
description: Returns the previous page in a global page collection, relative to the given page.
description: Returns the previous page in a site's collection of regular pages, relative to the current page.
categories: []
keywords: []
action:
related:
- methods/page/Next
- methods/page/PrevInSection
- methods/page/NextInSection
- methods/pages/Prev
- methods/page/PrevInSection
- methods/pages/Next
- methods/pages/Prev
returnType: page.Page
signatures: [PAGE.Prev]
toc: true
---
The behavior of the `Prev` and `Next` methods on a `Page` object is probably the reverse of what you expect.
With this content structure:
```text
content/
├── pages/
│ ├── _index.md
│ ├── page-1.md <-- front matter: weight = 10
│ ├── page-2.md <-- front matter: weight = 20
│ └── page-3.md <-- front matter: weight = 30
└── _index.md
```
When you visit page-2:
- The `Prev` method points to page-3
- The `Next` method points to page-1
{{% note %}}
Use the opposite label in your navigation links as shown in the example below.
{{% /note %}}
```go-html-template
{{ with .Next }}
<a href="{{ .RelPermalink }}">Prev</a>
{{ end }}
{{ with .Prev }}
<a href="{{ .RelPermalink }}">Next</a>
{{ end }}
```
## Compare to Pages methods
{{% include "methods/_common/next-prev-on-page-vs-next-prev-on-pages.md" %}}
{{% include "methods/page/_common/next-and-prev.md" %}}
+2 -59
View File
@@ -1,72 +1,15 @@
---
title: PrevInSection
description: Returns the previous page within a section, relative to the given page.
description: Returns the previous regular page in a section, relative to the given page.
categories: []
keywords: []
action:
related:
- methods/page/NextInSection
- methods/page/Next
- methods/pages/Next
- methods/page/Prev
- methods/pages/Prev
returnType: page.Page
signatures: [PAGE.PrevInSection]
---
The behavior of the `PrevInSection` and `NextInSection` methods on a `Page` object is probably the reverse of what you expect.
With this content structure:
```text
content/
├── books/
│ ├── _index.md
│ ├── book-1.md
│ ├── book-2.md
│ └── book-3.md
├── films/
│ ├── _index.md
│ ├── film-1.md
│ ├── film-2.md
│ └── film-3.md
└── _index.md
```
When you visit book-2:
- The `PrevInSection` method points to book-3
- The `NextInSection` method points to book-1
{{% note %}}
Use the opposite label in your navigation links as shown in the example below.
{{% /note %}}
```go-html-template
{{ with .NextInSection }}
<a href="{{ .RelPermalink }}">Previous in section</a>
{{ end }}
{{ with .PrevInSection }}
<a href="{{ .RelPermalink }}">Next in section</a>
{{ end }}
```
{{% note %}}
The navigation sort order may be different than the page collection sort order.
{{% /note %}}
With the `PrevInSection` and `NextInSection` methods, the navigation sort order is fixed, using Hugos default sort order. In order of precedence:
1. Page [weight]
2. Page [date] (descending)
3. Page [linkTitle], falling back to page [title]
4. Page file path if the page is backed by a file
For example, with a page collection sorted by title, the navigation sort order will use Hugos default sort order. This is probably not what you want or expect. For this reason, the Next and Prev methods on a Pages object are generally a better choice.
[date]: /methods/page/date/
[weight]: /methods/page/weight/
[linkTitle]: /methods/page/linktitle/
[title]: /methods/page/title/
{{% include "methods/page/_common/nextinsection-and-previnsection.md" %}}
@@ -6,6 +6,8 @@ keywords: []
action:
related:
- methods/page/Content
- methods/page/Summary
- methods/page/ContentWithoutSummary
- methods/page/Plain
- methods/page/PlainWords
- methods/page/RenderShortcodes
@@ -5,11 +5,13 @@ categories: []
keywords: []
action:
related:
- methods/page/RenderString
- methods/page/Content
- methods/page/Summary
- methods/page/ContentWithoutSummary
- methods/page/RawContent
- methods/page/Plain
- methods/page/PlainWords
- methods/page/RenderString
returnType: template.HTML
signatures: [PAGE.RenderShortcodes]
toc: true
@@ -0,0 +1,60 @@
---
# Do not remove front matter.
---
Hugo determines the _next_ and _previous_ page by sorting the site's collection of regular pages according to this sorting hierarchy:
Field|Precedence|Sort direction
:--|:--|:--
[`weight`]|1|descending
[`date`]|2|descending
[`linkTitle`]|3|descending
[`path`]|4|descending
[`date`]: /methods/page/date/
[`weight`]: /methods/page/weight/
[`linkTitle`]: /methods/page/linktitle/
[`path`]: /methods/page/path/
The sorted page collection used to determine the _next_ and _previous_ page is independent of other page collections, which may lead to unexpected behavior.
For example, with this content structure:
```text
content/
├── pages/
│ ├── _index.md
│ ├── page-1.md <-- front matter: weight = 10
│ ├── page-2.md <-- front matter: weight = 20
│ └── page-3.md <-- front matter: weight = 30
└── _index.md
```
And these templates:
{{< code file=layouts/_default/list.html >}}
{{ range .Pages.ByWeight }}
<h2><a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a></h2>
{{ end }}
{{< /code >}}
{{< code file=layouts/_default/single.html >}}
{{ with .Prev }}
<a href="{{ .RelPermalink }}">Previous</a>
{{ end }}
{{ with .Next }}
<a href="{{ .RelPermalink }}">Next</a>
{{ end }}
{{< /code >}}
When you visit page-2:
- The `Prev` method points to page-3
- The `Next` method points to page-1
To reverse the meaning of _next_ and _previous_ you can change the sort direction in your [site configuration], or use the [`Next`] and [`Prev`] methods on a `Pages` object for more flexibility.
[site configuration]: getting-started/configuration/#configure-page
[`Next`]: /methods/pages/prev
[`Prev`]: /methods/pages/prev
@@ -0,0 +1,78 @@
---
# Do not remove front matter.
---
Hugo determines the _next_ and _previous_ page by sorting the current section's regular pages according to this sorting hierarchy:
Field|Precedence|Sort direction
:--|:--|:--
[`weight`]|1|descending
[`date`]|2|descending
[`linkTitle`]|3|descending
[`path`]|4|descending
[`date`]: /methods/page/date/
[`weight`]: /methods/page/weight/
[`linkTitle`]: /methods/page/linktitle/
[`path`]: /methods/page/path/
The sorted page collection used to determine the _next_ and _previous_ page is independent of other page collections, which may lead to unexpected behavior.
For example, with this content structure:
```text
content/
├── pages/
│ ├── _index.md
│ ├── page-1.md <-- front matter: weight = 10
│ ├── page-2.md <-- front matter: weight = 20
│ └── page-3.md <-- front matter: weight = 30
└── _index.md
```
And these templates:
{{< code file=layouts/_default/list.html >}}
{{ range .Pages.ByWeight }}
<h2><a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a></h2>
{{ end }}
{{< /code >}}
{{< code file=layouts/_default/single.html >}}
{{ with .PrevInSection }}
<a href="{{ .RelPermalink }}">Previous</a>
{{ end }}
{{ with .NextInSection }}
<a href="{{ .RelPermalink }}">Next</a>
{{ end }}
{{< /code >}}
When you visit page-2:
- The `PrevInSection` method points to page-3
- The `NextInSection` method points to page-1
To reverse the meaning of _next_ and _previous_ you can change the sort direction in your [site configuration], or use the [`Next`] and [`Prev`] methods on a `Pages` object for more flexibility.
[site configuration]: getting-started/configuration/#configure-page
[`Next`]: /methods/pages/prev
[`Prev`]: /methods/pages/prev
## Example
Code defensively by checking for page existence:
```go-html-template
{{ with .PrevInSection }}
<a href="{{ .RelPermalink }}">Previous</a>
{{ end }}
{{ with .NextInSection }}
<a href="{{ .RelPermalink }}">Next</a>
{{ end }}
```
## Alternative
Use the [`Next`] and [`Prev`] methods on a `Pages` object for more flexibility.
+3 -41
View File
@@ -1,55 +1,17 @@
---
title: Next
description: Returns the next page in a local page collection, relative to the given page.
description: Returns the next page in a page collection, relative to the given page.
categories: []
keywords: []
action:
related:
- methods/pages/Prev
- methods/page/Next
- methods/page/NextInSection
- methods/page/Prev
- methods/page/NextInSection
- methods/page/PrevInSection
returnType: page.Page
signatures: [PAGES.Next PAGE]
toc: true
---
The behavior of the `Prev` and `Next` methods on a `Pages` objects is probably the reverse of what you expect.
With this content structure and the page collection sorted by weight in ascending order:
```text
content/
├── pages/
│ ├── _index.md
│ ├── page-1.md <-- front matter: weight = 10
│ ├── page-2.md <-- front matter: weight = 20
│ └── page-3.md <-- front matter: weight = 30
└── _index.md
```
When you visit page-2:
- The `Prev` method points to page-3
- The `Next` method points to page-1
{{% note %}}
Use the opposite label in your navigation links as shown in the example below.
{{% /note %}}
```go-html-template
{{ $pages := where .Site.RegularPages.ByWeight "Section" "pages" }}
{{ with $pages.Next . }}
<a href="{{ .RelPermalink }}">Previous</a>
{{ end }}
{{ with $pages.Prev . }}
<a href="{{ .RelPermalink }}">Next</a>
{{ end }}
```
## Compare to Page methods
{{% include "methods/_common/next-prev-on-page-vs-next-prev-on-pages.md" %}}
{{% include "methods/pages/_common/next-and-prev.md" %}}
+3 -41
View File
@@ -1,55 +1,17 @@
---
title: Prev
description: Returns the previous page in a local page collection, relative to the given page.
description: Returns the previous page in a page collection, relative to the given page.
categories: []
keywords: []
action:
related:
- methods/pages/Next
- methods/page/Next
- methods/page/NextInSection
- methods/page/Prev
- methods/page/NextInSection
- methods/page/PrevInSection
returnType: page.Pages
signatures: [PAGES.Prev PAGE]
toc: true
---
The behavior of the `Prev` and `Next` methods on a `Pages` objects is probably the reverse of what you expect.
With this content structure and the page collection sorted by weight in ascending order:
```text
content/
├── pages/
│ ├── _index.md
│ ├── page-1.md <-- front matter: weight = 10
│ ├── page-2.md <-- front matter: weight = 20
│ └── page-3.md <-- front matter: weight = 30
└── _index.md
```
When you visit page-2:
- The `Prev` method points to page-3
- The `Next` method points to page-1
{{% note %}}
Use the opposite label in your navigation links as shown in the example below.
{{% /note %}}
```go-html-template
{{ $pages := where .Site.RegularPages.ByWeight "Section" "pages" }}
{{ with $pages.Next . }}
<a href="{{ .RelPermalink }}">Previous</a>
{{ end }}
{{ with $pages.Prev . }}
<a href="{{ .RelPermalink }}">Next</a>
{{ end }}
```
## Compare to Page methods
{{% include "methods/_common/next-prev-on-page-vs-next-prev-on-pages.md" %}}
{{% include "methods/pages/_common/next-and-prev.md" %}}
@@ -0,0 +1,72 @@
---
# Do not remove front matter.
---
Hugo determines the _next_ and _previous_ page by sorting the page collection according to this sorting hierarchy:
Field|Precedence|Sort direction
:--|:--|:--
[`weight`]|1|descending
[`date`]|2|descending
[`linkTitle`]|3|descending
[`path`]|4|descending
[`date`]: /methods/page/date/
[`weight`]: /methods/page/weight/
[`linkTitle`]: /methods/page/linktitle/
[`path`]: /methods/page/path/
The sorted page collection used to determine the _next_ and _previous_ page is independent of other page collections, which may lead to unexpected behavior.
For example, with this content structure:
```text
content/
├── pages/
│ ├── _index.md
│ ├── page-1.md <-- front matter: weight = 10
│ ├── page-2.md <-- front matter: weight = 20
│ └── page-3.md <-- front matter: weight = 30
└── _index.md
```
And these templates:
{{< code file=layouts/_default/list.html >}}
{{ range .Pages.ByWeight}}
<h2><a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a></h2>
{{ end }}
{{< /code >}}
{{< code file=layouts/_default/single.html >}}
{{ $pages := .CurrentSection.Pages.ByWeight }}
{{ with $pages.Prev . }}
<a href="{{ .RelPermalink }}">Previous</a>
{{ end }}
{{ with $pages.Next . }}
<a href="{{ .RelPermalink }}">Next</a>
{{ end }}
{{< /code >}}
When you visit page-2:
- The `Prev` method points to page-3
- The `Next` method points to page-1
To reverse the meaning of _next_ and _previous_ you can chain the [`Reverse`] method to the page collection definition:
{{< code file=layouts/_default/single.html >}}
{{ $pages := .CurrentSection.Pages.ByWeight.Reverse }}
{{ with $pages.Prev . }}
<a href="{{ .RelPermalink }}">Previous</a>
{{ end }}
{{ with $pages.Next . }}
<a href="{{ .RelPermalink }}">Next</a>
{{ end }}
{{< /code >}}
[`Reverse`]: /methods/pages/reverse/
+207
View File
@@ -0,0 +1,207 @@
---
title: Blockquote render hooks
linkTitle: Blockquotes
description: Create a blockquote render hook to override the rendering of Markdown blockquotes to HTML.
categories: [render hooks]
keywords: []
menu:
docs:
parent: render-hooks
weight: 30
weight: 30
toc: true
---
{{< new-in 0.132.0 >}}
## Context
Blockquote render hook templates receive the following [context]:
[context]: /getting-started/glossary/#context
###### AlertType
(`string`) Applicable when [`Type`](#type) is `alert`, this is the alert type converted to lowercase. See the [alerts](#alerts) section below.
###### AlertTitle
{{< new-in 0.134.0 >}}
(`template.HTML`) Applicable when [`Type`](#type) is `alert`, this is the alert title. See the [alerts](#alerts) section below.
###### AlertSign
{{< new-in 0.134.0 >}}
(`string`) Applicable when [`Type`](#type) is `alert`, this is the alert sign. Typically used to indicate whether an alert is graphically foldable, this is one of&nbsp;`+`,&nbsp;`-`,&nbsp;or an empty string. See the [alerts](#alerts) section below.
###### Attributes
(`map`) The [Markdown attributes], available if you configure your site as follows:
[Markdown attributes]: /content-management/markdown-attributes/
{{< code-toggle file=hugo >}}
[markup.goldmark.parser.attribute]
block = true
{{< /code-toggle >}}
###### Ordinal
(`int`) The zero-based ordinal of the blockquote on the page.
###### Page
(`page`) A reference to the current page.
###### PageInner
(`page`) A reference to a page nested via the [`RenderShortcodes`] method. [See details](#pageinner-details).
[`RenderShortcodes`]: /methods/page/rendershortcodes
###### Position
(`string`) The position of the blockquote within the page content.
###### Text
(`template.HTML`) The blockquote text, excluding the first line if [`Type`](#type) is `alert`. See the [alerts](#alerts) section below.
###### Type
(`bool`) The blockquote type. Returns `alert` if the blockquote has an alert designator, else `regular`. See the [alerts](#alerts) section below.
## Examples
In its default configuration, Hugo renders Markdown blockquotes according to the [CommonMark specification]. To create a render hook that does the same thing:
[CommonMark specification]: https://spec.commonmark.org/current/
{{< code file=layouts/_default/_markup/render-blockquote.html copy=true >}}
<blockquote>
{{ .Text }}
</blockquote>
{{< /code >}}
To render a blockquote as an HTML `figure` element with an optional citation and caption:
{{< code file=layouts/_default/_markup/render-blockquote.html copy=true >}}
<figure>
<blockquote {{ with .Attributes.cite }}cite="{{ . }}"{{ end }}>
{{ .Text }}
</blockquote>
{{ with .Attributes.caption }}
<figcaption class="blockquote-caption">
{{ . | safeHTML }}
</figcaption>
{{ end }}
</figure>
{{< /code >}}
Then in your markdown:
```text
> Some text
{cite="https://gohugo.io" caption="Some caption"}
```
## Alerts
Also known as _callouts_ or _admonitions_, alerts are blockquotes used to emphasize critical information.
### Basic syntax
With the basic Markdown syntax, the first line of each alert is an alert designator consisting of an exclamation point followed by the alert type, wrapped within brackets. For example:
{{< code file=content/example.md lang=text >}}
> [!NOTE]
> Useful information that users should know, even when skimming content.
> [!TIP]
> Helpful advice for doing things better or more easily.
> [!IMPORTANT]
> Key information users need to know to achieve their goal.
> [!WARNING]
> Urgent info that needs immediate user attention to avoid problems.
> [!CAUTION]
> Advises about risks or negative outcomes of certain actions.
{{< /code >}}
The basic syntax is compatible with [GitHub], [Obsidian], and [Typora].
[GitHub]: https://docs.github.com/en/get-started/writing-on-github/getting-started-with-writing-and-formatting-on-github/basic-writing-and-formatting-syntax#alerts
[Obsidian]: https://help.obsidian.md/Editing+and+formatting/Callouts
[Typora]: https://support.typora.io/Markdown-Reference/#callouts--github-style-alerts
### Extended syntax
With the extended Markdown syntax, you may optionally include an alert sign and/or an alert title. The alert sign is one of&nbsp;`+`&nbsp;or&nbsp;`-`, typically used to indicate whether an alert is graphically foldable. For example:
{{< code file=content/example.md lang=text >}}
> [!WARNING]+ Radiation hazard
> Do not approach or handle without protective gear.
{{< /code >}}
The extended syntax is compatible with [Obsidian].
{{% note %}}
The extended syntax is not compatible with GitHub or Typora. If you include an alert sign or an alert title, these applications render the Markdown as a blockquote.
{{% /note %}}
### Example
This blockquote render hook renders a multilingual alert if an alert designator is present, otherwise it renders a blockquote according to the CommonMark specification.
{{< code file=layouts/_default/_markup/render-blockquote.html copy=true >}}
{{ $emojis := dict
"caution" ":exclamation:"
"important" ":information_source:"
"note" ":information_source:"
"tip" ":bulb:"
"warning" ":information_source:"
}}
{{ if eq .Type "alert" }}
<blockquote class="alert alert-{{ .AlertType }}">
<p class="alert-heading">
{{ transform.Emojify (index $emojis .AlertType) }}
{{ with .AlertTitle }}
{{ . }}
{{ else }}
{{ or (i18n .AlertType) (title .AlertType) }}
{{ end }}
</p>
{{ .Text }}
</blockquote>
{{ else }}
<blockquote>
{{ .Text }}
</blockquote>
{{ end }}
{{< /code >}}
To override the label, create these entries in your i18n files:
{{< code-toggle file=i18n/en.toml >}}
caution = 'Caution'
important = 'Important'
note = 'Note'
tip = 'Tip'
warning = 'Warning'
{{< /code-toggle >}}
Although you can use one template with conditional logic as shown above, you can also create separate templates for each [`Type`](#type) of blockquote:
```text
layouts/
└── _default/
└── _markup/
├── render-blockquote-alert.html
└── render-blockquote-regular.html
```
{{% include "/render-hooks/_common/pageinner.md" %}}
+2 -2
View File
@@ -7,8 +7,8 @@ keywords: []
menu:
docs:
parent: render-hooks
weight: 30
weight: 30
weight: 40
weight: 40
toc: true
---
+8 -6
View File
@@ -7,8 +7,8 @@ keywords: []
menu:
docs:
parent: render-hooks
weight: 40
weight: 40
weight: 50
weight: 50
toc: true
---
@@ -24,7 +24,9 @@ Heading render hook templates receive the following [context]:
###### Attributes
(`map`) The Markdown attributes, available if you configure your site as follows:
(`map`) The [Markdown attributes], available if you configure your site as follows:
[Markdown attributes]: /content-management/markdown-attributes/
{{< code-toggle file=hugo >}}
[markup.goldmark.parser.attribute]
@@ -53,7 +55,7 @@ title = true
###### Text
(`string`) The heading text.
(`template.HTML`) The heading text.
## Examples
@@ -63,7 +65,7 @@ In its default configuration, Hugo renders Markdown headings according to the [C
{{< code file=layouts/_default/_markup/render-heading.html copy=true >}}
<h{{ .Level }} id="{{ .Anchor }}">
{{- .Text | safeHTML -}}
{{- .Text -}}
</h{{ .Level }}>
{{< /code >}}
@@ -71,7 +73,7 @@ To add an anchor link to the right of each heading:
{{< code file=layouts/_default/_markup/render-heading.html copy=true >}}
<h{{ .Level }} id="{{ .Anchor }}">
{{ .Text | safeHTML }}
{{ .Text }}
<a href="#{{ .Anchor }}">#</a>
</h{{ .Level }}>
{{< /code >}}
+7 -5
View File
@@ -7,8 +7,8 @@ keywords: []
menu:
docs:
parent: render-hooks
weight: 50
weight: 50
weight: 60
weight: 60
toc: true
---
@@ -32,7 +32,9 @@ Image render hook templates receive the following context:
###### Attributes
(`map`) The Markdown attributes, available if you configure your site as follows:
(`map`) The [Markdown attributes], available if you configure your site as follows:
[Markdown attributes]: /content-management/markdown-attributes/
{{< code-toggle file=hugo >}}
[markup.goldmark.parser]
@@ -71,7 +73,7 @@ block = true
###### Text
(`string`) The image description.
(`template.HTML`) The image description.
###### Title
@@ -141,7 +143,7 @@ The embedded image render hook is automatically enabled for multilingual single-
[duplication of shared page resources]: /getting-started/configuration-markup/#duplicateresourcefiles
{{% /note %}}
The embedded image render hook resolves internal Markdown destinations by looking for a matching [page resource], falling back to a matching [global resource]. Remote destinations are passed through, and the render hook will not throw an error or warning if it is unable to resolve a destination.
The embedded image render hook resolves internal Markdown destinations by looking for a matching [page resource], falling back to a matching [global resource]. Remote destinations are passed through, and the render hook will not throw an error or warning if unable to resolve a destination.
[page resource]: /getting-started/glossary/#page-resource
[global resource]: /getting-started/glossary/#global-resource
+7 -1
View File
@@ -13,10 +13,13 @@ weight: 20
When rendering Markdown to HTML, render hooks override the conversion. Each render hook is a template, with one template for each supported element type:
- [Blockquotes](/render-hooks/blockquotes)
- [Code blocks](/render-hooks/code-blocks)
- [Headings](/render-hooks/headings)
- [Images](/render-hooks/images)
- [Links](/render-hooks/links)
- [Passthrough elements](/render-hooks/passthrough)
- [Tables](/render-hooks/tables)
{{% note %}}
Hugo supports multiple [content formats] including Markdown, HTML, AsciiDoc, Emacs Org Mode, Pandoc, and reStructuredText.
@@ -54,10 +57,13 @@ Each render hook is a template, with one template for each supported element typ
layouts/
└── _default/
└── _markup/
├── render-blockquote.html
├── render-codeblock.html
├── render-heading.html
├── render-image.html
── render-link.html
── render-link.html
├── render-passthrough.html
└── render-table.html
```
The template lookup order allows you to create different render hooks for each page [type], [kind], language, and [output format]. For example:
+6 -6
View File
@@ -7,8 +7,8 @@ keywords: []
menu:
docs:
parent: render-hooks
weight: 60
weight: 60
weight: 70
weight: 70
toc: true
---
@@ -54,7 +54,7 @@ Link render hook templates receive the following context:
###### Text
(`string`) The link description.
(`template.HTML`) The link description.
###### Title
@@ -74,7 +74,7 @@ In its default configuration, Hugo renders Markdown links according to the [Comm
<a href="{{ .Destination | safeURL }}"
{{- with .Title }} title="{{ . }}"{{ end -}}
>
{{- with .Text | safeHTML }}{{ . }}{{ end -}}
{{- with .Text }}{{ . }}{{ end -}}
</a>
{{- /* chomp trailing newline */ -}}
{{< /code >}}
@@ -87,7 +87,7 @@ To include a `rel` attribute set to `external` for external links:
{{- with .Title }} title="{{ . }}"{{ end -}}
{{- if $u.IsAbs }} rel="external"{{ end -}}
>
{{- with .Text | safeHTML }}{{ . }}{{ end -}}
{{- with .Text }}{{ . }}{{ end -}}
</a>
{{- /* chomp trailing newline */ -}}
{{< /code >}}
@@ -113,7 +113,7 @@ The embedded link render hook is automatically enabled for multilingual single-h
[duplication of shared page resources]: /getting-started/configuration-markup/#duplicateresourcefiles
{{% /note %}}
The embedded link render hook resolves internal Markdown destinations by looking for a matching page, falling back to a matching [page resource], then falling back to a matching [global resource]. Remote destinations are passed through, and the render hook will not throw an error or warning if it is unable to resolve a destination.
The embedded link render hook resolves internal Markdown destinations by looking for a matching page, falling back to a matching [page resource], then falling back to a matching [global resource]. Remote destinations are passed through, and the render hook will not throw an error or warning if unable to resolve a destination.
[page resource]: /getting-started/glossary/#page-resource
[global resource]: /getting-started/glossary/#global-resource
+125
View File
@@ -0,0 +1,125 @@
---
title: Passthrough render hooks
linkTitle: Passthrough
description: Create a passthrough render hook to override the rendering of text snippets captured by the Goldmark passthrough extension.
categories: [render hooks]
keywords: []
menu:
docs:
parent: render-hooks
weight: 80
weight: 80
toc: true
---
{{< new-in 0.132.0 >}}
## Overview
Hugo uses [Goldmark] to render Markdown to HTML. Goldmark supports custom extensions to extend its core functionality. The Goldmark [passthrough extension] captures and preserves raw Markdown within delimited snippets of text, including the delimiters themselves. These are known as _passthrough elements_.
[Goldmark]: https://github.com/yuin/goldmark
[passthrough extension]: /getting-started/configuration-markup/#passthrough
Depending on your choice of delimiters, Hugo will classify a passthrough element as either _block_ or _inline_. Consider this contrived example:
{{< code file=content/sample.md >}}
This is a
\[block\]
passthrough element with opening and closing block delimiters.
This is an \(inline\) passthrough element with opening and closing inline delimiters.
{{< /code >}}
Update your site configuration to enable the passthrough extension and define opening and closing delimiters for each passthrough element type, either `block` or `inline`. For example:
{{< code-toggle file=hugo >}}
[markup.goldmark.extensions.passthrough]
enable = true
[markup.goldmark.extensions.passthrough.delimiters]
block = [['\[', '\]'], ['$$', '$$']]
inline = [['\(', '\)']]
{{< /code-toggle >}}
In the example above there are two sets of `block` delimiters. You may use either one in your Markdown.
The Goldmark passthrough extension is often used in conjunction with the MathJax or KaTeX display engine to render [mathematical expressions] written in [LaTeX] or [Tex].
[mathematical expressions]: /content-management/mathematics/
[LaTeX]: https://www.latex-project.org/
[Tex]: https://en.wikipedia.org/wiki/TeX
To enable custom rendering of passthrough elements, create a render hook.
## Context
Passthrough render hook templates receive the following [context]:
[context]: /getting-started/glossary/#context
###### Attributes
(`map`) The [Markdown attributes], available if you configure your site as follows:
[Markdown attributes]: /content-management/markdown-attributes/
{{< code-toggle file=hugo >}}
[markup.goldmark.parser.attribute]
block = true
{{< /code-toggle >}}
Hugo populates the `Attributes` map for _block_ passthrough elements. Markdown attributes are not applicable to _inline_ elements.
###### Inner
(`string`) The inner content of the passthrough element, excluding the delimiters.
###### Ordinal
(`int`) The zero-based ordinal of the passthrough element on the page.
###### Page
(`page`) A reference to the current page.
###### PageInner
(`page`) A reference to a page nested via the [`RenderShortcodes`] method. [See details](#pageinner-details).
[`RenderShortcodes`]: /methods/page/rendershortcodes
###### Position
(`string`) The position of the passthrough element within the page content.
###### Type
(`bool`) The passthrough element type, either `block` or `inline`.
## Example
As an alternative to rendering mathematical expressions with the MathJax or KaTeX display engine, create a passthrough render hook which calls the [`transform.ToMath`] function:
[`transform.ToMath`]: /functions/transform/tomath/
{{< code file=layouts/_default/_markup/render-passthrough.html copy=true >}}
{{ if eq .Type "block" }}
{{ $opts := dict "displayMode" true }}
{{ transform.ToMath .Inner $opts }}
{{ else }}
{{ transform.ToMath .Inner }}
{{ end }}
{{< /code >}}
Although you can use one template with conditional logic as shown above, you can also create separate templates for each [`Type`](#type) of passthrough element:
```text
layouts/
└── _default/
└── _markup/
├── render-passthrough-block.html
└── render-passthrough-inline.html
```
{{% include "/render-hooks/_common/pageinner.md" %}}
+106
View File
@@ -0,0 +1,106 @@
---
title: Table render hooks
linkTitle: Tables
description: Create a table render hook to override the rendering of Markdown tables to HTML.
categories: [render hooks]
keywords: []
menu:
docs:
parent: render-hooks
weight: 90
weight: 90
toc: true
---
{{< new-in 0.134.0 >}}
## Context
Table render hook templates receive the following [context]:
[context]: /getting-started/glossary/#context
###### Attributes
(`map`) The [Markdown attributes], available if you configure your site as follows:
[Markdown attributes]: /content-management/markdown-attributes/
{{< code-toggle file=hugo >}}
[markup.goldmark.parser.attribute]
block = true
{{< /code-toggle >}}
###### Ordinal
(`int`) The zero-based ordinal of the table on the page.
###### Page
(`page`) A reference to the current page.
###### PageInner
(`page`) A reference to a page nested via the [`RenderShortcodes`] method. [See details](#pageinner-details).
[`RenderShortcodes`]: /methods/page/rendershortcodes
###### Position
(`string`) The position of the table within the page content.
###### THead
(`slice`) A slice of table header rows, where each element is a slice of table cells.
###### TBody
(`slice`) A slice of table body rows, where each element is a slice of table cells.
## Table cells
Each table cell within the slice of slices returned by the `THead` and `TBody` methods has the following fields:
###### Alignment
(`string`) The alignment of the text within the table cell, one of `left`, `center`, or `right`.
###### Text
(`template.HTML`) The text within the table cell.
## Example
In its default configuration, Hugo renders Markdown tables according to the [GitHub Flavored Markdown specification]. To create a render hook that does the same thing:
[GitHub Flavored Markdown specification]: https://github.github.com/gfm/#tables-extension-
{{< code file=layouts/_default/_markup/render-table.html copy=true >}}
<table
{{- range $k, $v := .Attributes }}
{{- if $v }}
{{- printf " %s=%q" $k $v | safeHTMLAttr }}
{{- end }}
{{- end }}>
<thead>
{{- range .THead }}
<tr>
{{- range . }}
<th {{ printf "style=%q" (printf "text-align: %s" .Alignment) | safeHTMLAttr }}>
{{- .Text -}}
</th>
{{- end }}
</tr>
{{- end }}
</thead>
<tbody>
{{- range .TBody }}
<tr>
{{- range . }}
<td {{ printf "style=%q" (printf "text-align: %s" .Alignment) | safeHTMLAttr }}>
{{- .Text -}}
</td>
{{- end }}
</tr>
{{- end }}
</tbody>
</table>
{{< /code >}}
{{% include "/render-hooks/_common/pageinner.md" %}}
+2 -2
View File
@@ -135,7 +135,7 @@ tags = []
Hugo uses the page title and description for the title and description metadata.
The first 6 URLs from the `images` array are used for image metadata.
If [page bundles](/content-management/page-bundles/) are used and the `images` array is empty or undefined, images with file names matching `*feature*` or `*cover*,*thumbnail*` are used for image metadata.
If [page bundles](/content-management/page-bundles/) are used and the `images` array is empty or undefined, images with file names matching `*feature*`, `*cover*`, or `*thumbnail*` are used for image metadata.
Various optional metadata can also be set:
@@ -203,7 +203,7 @@ description = "Text about this post"
images = ["post-cover.png"]
{{</ code-toggle >}}
If `images` aren't specified in the page front-matter, then hugo searches for [image page resources](/content-management/image-processing/) with `feature`, `cover`, or `thumbnail` in their name.
If [page bundles](/content-management/page-bundles/) are used and the `images` array is empty or undefined, images with file names matching `*feature*`, `*cover*`, or `*thumbnail*` are used for image metadata.
If no image resources with those names are found, the images defined in the [site config](/getting-started/configuration/) are used instead.
If no images are found at all, then an image-less Twitter `summary` card is used instead of `summary_large_image`.
+14
View File
@@ -509,6 +509,20 @@ See documentation for [`with`], [`else`], and [`end`].
{{ end }}
```
To test multiple conditions:
```go-html-template
{{ $v1 := 0 }}
{{ $v2 := 42 }}
{{ with $v1 }}
{{ . }}
{{ else with $v2 }}
{{ . }} → 42
{{ else }}
{{ print "v1 and v2 are falsy" }}
{{ end }}
```
### Access site parameters
See documentation for the [`Params`](/methods/site/params/) method on a `Site` object.
+1 -1
View File
@@ -129,5 +129,5 @@ Hugo provides two methods to localize your menu entries. See [multilingual].
[localize the menu entries]: /content-management/multilingual/#menus
[menu entry defined in front matter]: /content-management/menus/#example-front-matter
[menu entry defined in site configuration]: /content-management/menus/#example-site-configuration
[menu and methods]: /methods/menu/
[menu methods]: /methods/menu/
[multilingual]: /content-management/multilingual/#menus
+21 -4
View File
@@ -37,12 +37,29 @@ You can organize your shortcodes in subdirectories, e.g. in `layouts/shortcodes/
Note the forward slash.
### Shortcode template lookup order
### Template lookup order
Shortcode templates have a simple [lookup order]:
Hugo selects shortcode templates based on the shortcode name, the current output format, and the current language. The examples below are sorted by specificity in descending order. The least specific path is at the bottom of the list.
1. `/layouts/shortcodes/<SHORTCODE>.html`
2. `/themes/<THEME>/layouts/shortcodes/<SHORTCODE>.html`
Shortcode name|Output format|Language|Template path
:--|:--|:--|:--
foo|html|en|layouts/shortcodes/foo.en.html
foo|html|en|layouts/shortcodes/foo.html.html
foo|html|en|layouts/shortcodes/foo.html
foo|html|en|layouts/shortcodes/foo.html.en.html
Shortcode name|Output format|Language|Template path
:--|:--|:--|:--
foo|rss|en|layouts/shortcodes/foo.en.xml
foo|rss|en|layouts/shortcodes/foo.rss.xml
foo|rss|en|layouts/shortcodes/foo.en.html
foo|rss|en|layouts/shortcodes/foo.rss.en.xml
foo|rss|en|layouts/shortcodes/foo.xml
foo|rss|en|layouts/shortcodes/foo.html.en.html
foo|rss|en|layouts/shortcodes/foo.html.html
foo|rss|en|layouts/shortcodes/foo.html
Note that templates provided by a theme or module always take precedence.
### Positional vs. named arguments
+7 -7
View File
@@ -13,9 +13,9 @@ toc: true
aliases: [/developer-tools/migrations/, /developer-tools/migrated/]
---
This section highlights some projects around Hugo that are independently developed. These tools try to extend the functionality of our static site generator or help you to get started.
This section highlights some independently developed projects related to Hugo. These tools extend functionality or help you to get started.
Take a look at this list of migration tools if you currently use other blogging tools like Jekyll or WordPress but intend to switch to Hugo instead. They'll take care to export your content into Hugo-friendly formats.
Take a look at this list of migration tools if you currently use other blogging tools like Jekyll or WordPress but intend to switch to Hugo instead. They'll help you export your content into Hugo-friendly formats.
## Jekyll
@@ -35,18 +35,18 @@ Alternatively, you can use the [Jekyll import command](/commands/hugo_import_jek
## DokuWiki
[dokuwiki-to-hugo](https://github.com/wgroeneveld/dokuwiki-to-hugo)
: Migrates your DokuWiki source pages from [DokuWiki syntax](https://www.dokuwiki.org/wiki:syntax) to Hugo Markdown syntax. Includes extra's like the TODO plugin. Written with extensibility in mind using python 3. Also generates a TOML header for each page. Designed to copypaste the wiki directory into your /content directory.
: Migrates your DokuWiki source pages from [DokuWiki syntax](https://www.dokuwiki.org/wiki:syntax) to Hugo Markdown syntax. Includes extras like the TODO plugin. Written with extensibility in mind using Python 3. Also generates a TOML header for each page. Designed to copy-paste the wiki directory into your /content directory.
## WordPress
[wordpress-to-hugo-exporter](https://github.com/SchumacherFM/wordpress-to-hugo-exporter)
: A one-click WordPress plugin that converts all posts, pages, taxonomies, metadata, and settings to Markdown and YAML which can be dropped into Hugo. (Note: If you have trouble using this plugin, you can [export your site for Jekyll](https://wordpress.org/plugins/jekyll-exporter/) and use Hugo's built in Jekyll converter listed above.)
: A one-click WordPress plugin that converts all posts, pages, taxonomies, metadata, and settings to Markdown and YAML which can be dropped into Hugo. (Note: If you have trouble using this plugin, you can [export your site for Jekyll](https://wordpress.org/plugins/jekyll-exporter/) and use Hugo's built-in Jekyll converter listed above.)
[blog2md](https://github.com/palaniraja/blog2md)
: Works with [exported xml](https://en.support.wordpress.com/export/) file of your free YOUR-TLD.wordpress.com website. It also saves approved comments to `YOUR-POST-NAME-comments.md` file along with posts.
[wordhugopress](https://github.com/nantipov/wordhugopress)
: A small utility written in Java, exports the entire WordPress site from the database and resource (e.g. images) files stored locally or remotely. Therefore, migration from the backup files is possible. Supports merging of the multiple WordPress sites into a single Hugo one.
: A small utility written in Java that exports the entire WordPress site from the database and resource (e.g., images) files stored locally or remotely. Therefore, migration from the backup files is possible. Supports merging multiple WordPress sites into a single Hugo site.
[wp2hugo](https://github.com/ashishb/wp2hugo)
: A Go-based CLI tool to migrate WordPress website to Hugo while preserving original URLs, GUIDs (for feeds), image URLs, code highlights, table of contents, YouTube embeds, Google Maps embeds, and original WordPress navigation categories.
@@ -57,7 +57,7 @@ Alternatively, you can use the [Jekyll import command](/commands/hugo_import_jek
: A simple Medium to Hugo exporter able to import stories in one command, including front matter.
[medium-to-hugo](https://github.com/bgadrian/medium-to-hugo)
: CLI tool written in Go to export medium posts into a Hugo compatible Markdown format. Tags and images are included. All images will be downloaded locally and linked appropriately.
: A CLI tool written in Go to export medium posts into a Hugo-compatible Markdown format. Tags and images are included. All images will be downloaded locally and linked appropriately.
## Tumblr
@@ -68,7 +68,7 @@ Alternatively, you can use the [Jekyll import command](/commands/hugo_import_jek
: Export all your Tumblr content to Hugo Markdown files with preserved original formatting.
[Tumblr to Hugo](https://github.com/jipiboily/tumblr-to-hugo)
: A migration tool that converts each of your Tumblr posts to a content file with a proper title and path. Furthermore, "Tumblr to Hugo" creates a CSV file with the original URL and the new path on Hugo, to help you setup the redirections.
: A migration tool that converts each of your Tumblr posts to a content file with a proper title and path. It also generates a CSV file to help you set up URL redirects.
## Drupal
+4
View File
@@ -43,6 +43,10 @@ A static website with a dynamic search function? Yes, Hugo provides an alternati
[Hugo Lyra](https://github.com/paolomainardi/hugo-lyra)
: Hugo-Lyra is a JavaScript module to integrate [Lyra](https://github.com/LyraSearch/lyra) into a Hugo website. It contains the server-side part to generate the index and the client-side library (optional) to bootstrap the search engine easily.
[INFINI Pizza for WebAssembly](https://github.com/infinilabs/pizza-docsearch)
: Pizza is a super-lightweight yet fully featured search engine written in Rust. You can quickly add offline search functionality to your Hugo website in just five minutes with only three lines of code. For a step-by-step guide on integrating it with Hugo, check out [this blog tutorial](https://dev.to/medcl/adding-search-functionality-to-a-hugo-static-site-based-on-infini-pizza-for-webassembly-4h5e).
## Commercial
[Algolia](https://www.algolia.com/)
+1 -1
View File
@@ -2,4 +2,4 @@ module github.com/gohugoio/hugoDocs
go 1.16
require github.com/gohugoio/gohugoioTheme v0.0.0-20240728210410-d42c342ce472 // indirect
require github.com/gohugoio/gohugoioTheme v0.0.0-20240815082608-66ccd383a90f // indirect
+4
View File
@@ -10,3 +10,7 @@ github.com/gohugoio/gohugoioTheme v0.0.0-20240623150114-cc7096eab3fd h1:I8X7c0oB
github.com/gohugoio/gohugoioTheme v0.0.0-20240623150114-cc7096eab3fd/go.mod h1:GOYeAPQJ/ok8z7oz1cjfcSlsFpXrmx6VkzQ5RpnyhZM=
github.com/gohugoio/gohugoioTheme v0.0.0-20240728210410-d42c342ce472 h1:AYZUibKKFRBp2VCQpDHW+JmQKvCvyhX7z7/SOLUSCcw=
github.com/gohugoio/gohugoioTheme v0.0.0-20240728210410-d42c342ce472/go.mod h1:GOYeAPQJ/ok8z7oz1cjfcSlsFpXrmx6VkzQ5RpnyhZM=
github.com/gohugoio/gohugoioTheme v0.0.0-20240812175901-cc0ef8e4a14a h1:E3JbZo69eqFBz6B+meQlKyy/ZBZQ73ldVDw8TADiIrQ=
github.com/gohugoio/gohugoioTheme v0.0.0-20240812175901-cc0ef8e4a14a/go.mod h1:GOYeAPQJ/ok8z7oz1cjfcSlsFpXrmx6VkzQ5RpnyhZM=
github.com/gohugoio/gohugoioTheme v0.0.0-20240815082608-66ccd383a90f h1:Eo5z3uUYfmrtIxQvHm388dFOERZwWGTjLuUO6vobzLc=
github.com/gohugoio/gohugoioTheme v0.0.0-20240815082608-66ccd383a90f/go.mod h1:GOYeAPQJ/ok8z7oz1cjfcSlsFpXrmx6VkzQ5RpnyhZM=
+3 -1
View File
@@ -5,7 +5,6 @@ defaultContentLanguage = "en"
enableEmoji = true
ignoreErrors = ["error-remote-getjson", "error-missing-instagram-accesstoken"]
languageCode = "en-us"
paginate = 100
pluralizeListTitles = false
timeZone = "Europe/Oslo"
title = "Hugo"
@@ -13,6 +12,9 @@ title = "Hugo"
# We do redirects via Netlify's _redirects file, generated by Hugo (see "outputs" below).
disableAliases = true
[pagination]
pagerSize = 100
[services.googleAnalytics]
ID = 'G-MBZGKNMDWC'
+1 -1
View File
@@ -3,7 +3,7 @@
command = "hugo --gc --minify"
[build.environment]
HUGO_VERSION = "0.131.0"
HUGO_VERSION = "0.134.0"
[context.production.environment]
HUGO_ENV = "production"
+6 -5
View File
@@ -504,7 +504,7 @@ type contentTableOfContents struct {
}
type contentSummary struct {
content string
content template.HTML
contentWithoutSummary template.HTML
summary page.Summary
}
@@ -612,9 +612,9 @@ func (c *cachedContentScope) contentRendered(ctx context.Context) (contentSummar
Truncated: summarized.Truncated(),
}
result.contentWithoutSummary = template.HTML(summarized.ContentWithoutSummary())
result.content = summarized.Content()
result.content = template.HTML(summarized.Content())
} else {
result.content = string(b)
result.content = template.HTML(string(b))
}
if !c.pi.hasSummaryDivider && cp.po.p.m.pageConfig.Summary == "" {
@@ -646,6 +646,7 @@ func (c *cachedContentScope) contentRendered(ctx context.Context) (contentSummar
Text: helpers.BytesToHTML(html),
Type: page.SummaryTypeFrontMatter,
}
rs.Value.contentWithoutSummary = rs.Value.content
}
return rs, err
@@ -879,7 +880,7 @@ func (c *cachedContentScope) Content(ctx context.Context) (template.HTML, error)
if err != nil {
return "", err
}
return template.HTML(cr.content), nil
return cr.content, nil
}
func (c *cachedContentScope) ContentWithoutSummary(ctx context.Context) (template.HTML, error) {
@@ -928,7 +929,7 @@ func (c *cachedContentScope) RenderString(ctx context.Context, args ...any) (tem
contentToRenderv := args[sidx]
if _, ok := contentToRenderv.(hstring.RenderedHTML); ok {
if _, ok := contentToRenderv.(hstring.HTML); ok {
// This content is already rendered, this is potentially
// a infinite recursion.
return "", errors.New("text is already rendered, repeating it may cause infinite recursion")
+2 -2
View File
@@ -523,7 +523,7 @@ categories: ["cool stuff"]
for _, p := range s.Pages() {
checkDated(p, p.Kind())
}
checkDate(s.LastChange(), "site")
checkDate(s.Lastmod(), "site")
}
func TestPageDatesSections(t *testing.T) {
@@ -593,7 +593,7 @@ func TestPageSummary(t *testing.T) {
// Source is not Asciidoctor- or RST-compatible so don't test them
if ext != "ad" && ext != "rst" {
checkPageContent(t, p, normalizeExpected(ext, "<p><a href=\"https://lipsum.com/\">Lorem ipsum</a> dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>\n\n<p>Additional text.</p>\n\n<p>Further text.</p>\n"), ext)
checkPageSummary(t, p, normalizeExpected(ext, "<p><a href=\"https://lipsum.com/\">Lorem ipsum</a> dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>"), ext)
checkPageSummary(t, p, normalizeExpected(ext, "<p><a href=\"https://lipsum.com/\">Lorem ipsum</a> dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p><p>Additional text.</p>"), ext)
}
checkPageType(t, p, "page")
}
-29
View File
@@ -185,35 +185,6 @@ urls="none"
[security.http]
mediaTypes=["application/json"]
`)
})
})
c.Run("getJSON, OK", func(c *qt.C) {
c.Parallel()
httpTestVariant(c, `{{ $json := getJSON "%[1]s/fruits.json" }}{{ $json.Content }}`, "", nil)
})
c.Run("getJSON, denied URL", func(c *qt.C) {
c.Parallel()
httpTestVariant(c, `{{ $json := getJSON "%[1]s/fruits.json" }}{{ $json.Content }}`, `(?s).*is not whitelisted in policy "security\.http\.urls".*`,
func(b *sitesBuilder) {
b.WithConfigFile("toml", `
[security]
[security.http]
urls="none"
`)
})
})
c.Run("getCSV, denied URL", func(c *qt.C) {
c.Parallel()
httpTestVariant(c, `{{ $d := getCSV ";" "%[1]s/cities.csv" }}{{ $d.Content }}`, `(?s).*is not whitelisted in policy "security\.http\.urls".*`,
func(b *sitesBuilder) {
b.WithConfigFile("toml", `
[security]
[security.http]
urls="none"
`)
})
})
+1 -2
View File
@@ -121,11 +121,10 @@ date: 2023-04-01
---
-- layouts/index.html --
site.Lastmod: {{ .Site.Lastmod.Format "2006-01-02" }}
site.LastChange: {{ .Site.LastChange.Format "2006-01-02" }}
home.Lastmod: {{ site.Home.Lastmod.Format "2006-01-02" }}
`
b := Test(t, files)
b.AssertFileContent("public/index.html", "site.Lastmod: 2023-04-01\nsite.LastChange: 2023-04-01\nhome.Lastmod: 2023-01-01")
b.AssertFileContent("public/index.html", "site.Lastmod: 2023-04-01\nhome.Lastmod: 2023-01-01")
}
+2 -2
View File
@@ -147,8 +147,8 @@ func TestLastChange(t *testing.T) {
s := buildSingleSite(t, deps.DepsCfg{Fs: fs, Configs: configs}, BuildCfg{SkipRender: true})
c.Assert(s.LastChange().IsZero(), qt.Equals, false)
c.Assert(s.LastChange().Year(), qt.Equals, 2017)
c.Assert(s.Lastmod().IsZero(), qt.Equals, false)
c.Assert(s.Lastmod().Year(), qt.Equals, 2017)
}
// Issue #_index
+5 -2
View File
@@ -1,7 +1,10 @@
# Release env.
# These will be replaced by script before release.
HUGORELEASER_TAG=v0.133.1
HUGORELEASER_COMMITISH=47d00202e7e61769ce4d14691e43b27852c9cce4
HUGORELEASER_TAG=v0.134.2
HUGORELEASER_COMMITISH=1c74abd26070b0c12849550c974a9f3f1e7afb06
+14 -4
View File
@@ -41,7 +41,7 @@ type LinkContext interface {
Title() string
// The rendered (HTML) text.
Text() hstring.RenderedHTML
Text() hstring.HTML
// The plain variant of Text.
PlainText() string
@@ -100,7 +100,7 @@ type BlockquoteContext interface {
// The blockquote text.
// If type is "alert", this will be the alert text.
Text() hstring.RenderedHTML
Text() hstring.HTML
/// Returns the blockquote type, one of "regular" and "alert".
// Type "alert" indicates that this is a GitHub type alert.
@@ -109,6 +109,16 @@ type BlockquoteContext interface {
// The GitHub alert type converted to lowercase, e.g. "note".
// Only set if Type is "alert".
AlertType() string
// The alert title.
// Currently only relevant for Obsidian alerts.
// GitHub does not suport alert titles and will not render alerts with titles.
AlertTitle() hstring.HTML
// The alert sign, "+" or "-" or "" used to indicate folding.
// Currently only relevant for Obsidian alerts.
// GitHub does not suport alert signs and will not render alerts with signs.
AlertSign() string
}
type PositionerSourceTargetProvider interface {
@@ -166,7 +176,7 @@ type HeadingContext interface {
// Anchor is the HTML id assigned to the heading.
Anchor() string
// Text is the rendered (HTML) heading text, excluding the heading marker.
Text() hstring.RenderedHTML
Text() hstring.HTML
// PlainText is the unrendered version of Text.
PlainText() string
@@ -213,7 +223,7 @@ const (
type GetRendererFunc func(t RendererType, id any) any
type TableCell struct {
Text hstring.RenderedHTML
Text hstring.HTML
Alignment string // left, center, or right
}
+38 -23
View File
@@ -74,8 +74,8 @@ func (r *htmlRenderer) renderBlockquote(w util.BufWriter, src []byte, node ast.N
ordinal := ctx.GetAndIncrementOrdinal(ast.KindBlockquote)
typ := typeRegular
alertType := resolveGitHubAlert(string(text))
if alertType != "" {
alert := resolveBlockQuoteAlert(string(text))
if alert.typ != "" {
typ = typeAlert
}
@@ -94,8 +94,8 @@ func (r *htmlRenderer) renderBlockquote(w util.BufWriter, src []byte, node ast.N
bqctx := &blockquoteContext{
BaseContext: render.NewBaseContext(ctx, renderer, n, src, nil, ordinal),
typ: typ,
alertType: alertType,
text: hstring.RenderedHTML(text),
alert: alert,
text: hstring.HTML(text),
AttributesHolder: attributes.New(n.Attributes(), attributes.AttributesOwnerGeneral),
}
@@ -133,11 +133,9 @@ func (r *htmlRenderer) renderBlockquoteDefault(
type blockquoteContext struct {
hooks.BaseContext
text hstring.RenderedHTML
alertType string
typ string
text hstring.HTML
typ string
alert blockQuoteAlert
*attributes.AttributesHolder
}
@@ -146,25 +144,42 @@ func (c *blockquoteContext) Type() string {
}
func (c *blockquoteContext) AlertType() string {
return c.alertType
return c.alert.typ
}
func (c *blockquoteContext) Text() hstring.RenderedHTML {
func (c *blockquoteContext) AlertTitle() hstring.HTML {
return hstring.HTML(c.alert.title)
}
func (c *blockquoteContext) AlertSign() string {
return c.alert.sign
}
func (c *blockquoteContext) Text() hstring.HTML {
return c.text
}
// https://docs.github.com/en/get-started/writing-on-github/getting-started-with-writing-and-formatting-on-github/basic-writing-and-formatting-syntax#alerts
// Five types:
// [!NOTE], [!TIP], [!WARNING], [!IMPORTANT], [!CAUTION]
// Note that GitHub's implementation is case-insensitive.
var gitHubAlertRe = regexp.MustCompile(`(?i)^<p>\[!(NOTE|TIP|WARNING|IMPORTANT|CAUTION)\]`)
var blockQuoteAlertRe = regexp.MustCompile(`^<p>\[!([a-zA-Z]+)\](-|\+)?[^\S\r\n]?([^\n]*)\n?`)
// resolveGitHubAlert returns one of note, tip, warning, important or caution.
// An empty string if no match.
func resolveGitHubAlert(s string) string {
m := gitHubAlertRe.FindStringSubmatch(s)
if len(m) == 2 {
return strings.ToLower(m[1])
func resolveBlockQuoteAlert(s string) blockQuoteAlert {
m := blockQuoteAlertRe.FindStringSubmatch(s)
if len(m) == 4 {
title := strings.TrimSpace(m[3])
title = strings.TrimRight(title, "</p>")
return blockQuoteAlert{
typ: strings.ToLower(m[1]),
sign: m[2],
title: title,
}
}
return ""
return blockQuoteAlert{}
}
// Blockquote alert syntax was introduced by GitHub, but is also used
// by Obsidian which also support some extended attributes: More types, alert titles and a +/- sign for folding.
type blockQuoteAlert struct {
typ string
sign string
title string
}
@@ -76,7 +76,7 @@ title: "p1"
`
b := hugolib.Test(t, files)
b.AssertFileContent("public/p1/index.html",
b.AssertFileContentExact("public/p1/index.html",
"Blockquote Alert: |<p>This is a note with some whitespace after the alert type.</p>\n|alert|",
"Blockquote Alert: |<p>This is a tip.</p>",
"Blockquote Alert: |<p>This is a caution with some whitespace before the alert type.</p>\n|alert|",
@@ -107,5 +107,52 @@ Content: {{ .Content }}
`
b := hugolib.Test(t, files)
b.AssertFileContent("public/p1/index.html", "Content: <blockquote>\n</blockquote>\n")
b.AssertFileContentExact("public/p1/index.html", "Content: <blockquote>\n</blockquote>\n")
}
func TestBlockquObsidianWithTitleAndSign(t *testing.T) {
t.Parallel()
files := `
-- hugo.toml --
-- content/_index.md --
---
title: "Home"
---
> [!danger]
> Do not approach or handle without protective gear.
> [!tip] Callouts can have custom titles
> Like this one.
> [!tip] Title-only callout
> [!faq]- Foldable negated callout
> Yes! In a foldable callout, the contents are hidden when the callout is collapsed
> [!faq]+ Foldable callout
> Yes! In a foldable callout, the contents are hidden when the callout is collapsed
> [!info] Can callouts be nested?
> > [!important] Yes!, they can.
> > > [!tip] You can even use multiple layers of nesting.
-- layouts/index.html --
{{ .Content }}
-- layouts/_default/_markup/render-blockquote.html --
AlertType: {{ .AlertType }}|AlertTitle: {{ .AlertTitle }}|AlertSign: {{ .AlertSign | safeHTML }}|Text: {{ .Text }}|
`
b := hugolib.Test(t, files)
b.AssertFileContentExact("public/index.html",
"AlertType: tip|AlertTitle: Callouts can have custom titles|AlertSign: |",
"AlertType: tip|AlertTitle: Title-only callout|AlertSign: |",
"AlertType: faq|AlertTitle: Foldable negated callout|AlertSign: -|Text: <p>Yes! In a foldable callout, the contents are hidden when the callout is collapsed</p>\n|",
"AlertType: faq|AlertTitle: Foldable callout|AlertSign: +|Text: <p>Yes! In a foldable callout, the contents are hidden when the callout is collapsed</p>\n|",
"AlertType: danger|AlertTitle: |AlertSign: |Text: <p>Do not approach or handle without protective gear.</p>\n|",
"AlertTitle: Can callouts be nested?|",
"AlertTitle: You can even use multiple layers of nesting.|",
)
}
+23 -15
View File
@@ -19,42 +19,50 @@ import (
qt "github.com/frankban/quicktest"
)
func TestResolveGitHubAlert(t *testing.T) {
func TestResolveBlockQuoteAlert(t *testing.T) {
t.Parallel()
c := qt.New(t)
tests := []struct {
input string
expected string
expected blockQuoteAlert
}{
{
input: "[!NOTE]",
expected: "note",
expected: blockQuoteAlert{typ: "note"},
},
{
input: "[!WARNING]",
expected: "warning",
input: "[!FaQ]",
expected: blockQuoteAlert{typ: "faq"},
},
{
input: "[!TIP]",
expected: "tip",
input: "[!NOTE]+",
expected: blockQuoteAlert{typ: "note", sign: "+"},
},
{
input: "[!IMPORTANT]",
expected: "important",
input: "[!NOTE]-",
expected: blockQuoteAlert{typ: "note", sign: "-"},
},
{
input: "[!CAUTION]",
expected: "caution",
input: "[!NOTE] This is a note",
expected: blockQuoteAlert{typ: "note", title: "This is a note"},
},
{
input: "[!FOO]",
expected: "",
input: "[!NOTE]+ This is a note",
expected: blockQuoteAlert{typ: "note", sign: "+", title: "This is a note"},
},
{
input: "[!NOTE]+ This is a title\nThis is not.",
expected: blockQuoteAlert{typ: "note", sign: "+", title: "This is a title"},
},
{
input: "[!NOTE]\nThis is not.",
expected: blockQuoteAlert{typ: "note"},
},
}
for _, test := range tests {
c.Assert(resolveGitHubAlert("<p>"+test.input), qt.Equals, test.expected)
for i, test := range tests {
c.Assert(resolveBlockQuoteAlert("<p>"+test.input+"</p>"), qt.Equals, test.expected, qt.Commentf("Test %d", i))
}
}
+8 -8
View File
@@ -52,7 +52,7 @@ type linkContext struct {
pageInner any
destination string
title string
text hstring.RenderedHTML
text hstring.HTML
plainText string
*attributes.AttributesHolder
}
@@ -69,7 +69,7 @@ func (ctx linkContext) PageInner() any {
return ctx.pageInner
}
func (ctx linkContext) Text() hstring.RenderedHTML {
func (ctx linkContext) Text() hstring.HTML {
return ctx.text
}
@@ -100,7 +100,7 @@ type headingContext struct {
pageInner any
level int
anchor string
text hstring.RenderedHTML
text hstring.HTML
plainText string
*attributes.AttributesHolder
}
@@ -121,7 +121,7 @@ func (ctx headingContext) Anchor() string {
return ctx.anchor
}
func (ctx headingContext) Text() hstring.RenderedHTML {
func (ctx headingContext) Text() hstring.HTML {
return ctx.text
}
@@ -199,7 +199,7 @@ func (r *hookedRenderer) renderImage(w util.BufWriter, source []byte, node ast.N
pageInner: pageInner,
destination: string(n.Destination),
title: string(n.Title),
text: hstring.RenderedHTML(text),
text: hstring.HTML(text),
plainText: string(n.Text(source)),
AttributesHolder: attributes.New(attrs, attributes.AttributesOwnerGeneral),
},
@@ -288,7 +288,7 @@ func (r *hookedRenderer) renderLink(w util.BufWriter, source []byte, node ast.No
pageInner: pageInner,
destination: string(n.Destination),
title: string(n.Title),
text: hstring.RenderedHTML(text),
text: hstring.HTML(text),
plainText: string(n.Text(source)),
AttributesHolder: attributes.Empty,
},
@@ -355,7 +355,7 @@ func (r *hookedRenderer) renderAutoLink(w util.BufWriter, source []byte, node as
page: page,
pageInner: pageInner,
destination: url,
text: hstring.RenderedHTML(label),
text: hstring.HTML(label),
plainText: label,
AttributesHolder: attributes.Empty,
},
@@ -442,7 +442,7 @@ func (r *hookedRenderer) renderHeading(w util.BufWriter, source []byte, node ast
pageInner: pageInner,
level: n.Level,
anchor: string(anchor),
text: hstring.RenderedHTML(text),
text: hstring.HTML(text),
plainText: string(n.Text(source)),
AttributesHolder: attributes.New(n.Attributes(), attributes.AttributesOwnerGeneral),
},
+1 -1
View File
@@ -132,7 +132,7 @@ func (r *htmlRenderer) renderCell(w util.BufWriter, source []byte, node ast.Node
alignment = "left"
}
cell := hooks.TableCell{Text: hstring.RenderedHTML(text), Alignment: alignment}
cell := hooks.TableCell{Text: hstring.HTML(text), Alignment: alignment}
if node.Parent().Kind() == gast.KindTableHeader {
table.THead[len(table.THead)-1] = append(table.THead[len(table.THead)-1], cell)
+19 -1
View File
@@ -161,6 +161,16 @@ func (s *HtmlSummary) resolveParagraphTagAndSetWrapper(mt media.Type) tagReStart
return ptag
}
// Avoid counting words that are most likely HTML tokens.
var (
isProbablyHTMLTag = regexp.MustCompile(`^<\/?[A-Za-z]+>?$`)
isProablyHTMLAttribute = regexp.MustCompile(`^[A-Za-z]+=["']`)
)
func isProbablyHTMLToken(s string) bool {
return s == ">" || isProbablyHTMLTag.MatchString(s) || isProablyHTMLAttribute.MatchString(s)
}
// ExtractSummaryFromHTML extracts a summary from the given HTML content.
func ExtractSummaryFromHTML(mt media.Type, input string, numWords int, isCJK bool) (result HtmlSummary) {
result.source = input
@@ -173,6 +183,14 @@ func ExtractSummaryFromHTML(mt media.Type, input string, numWords int, isCJK boo
var count int
countWord := func(word string) int {
word = strings.TrimSpace(word)
if len(word) == 0 {
return 0
}
if isProbablyHTMLToken(word) {
return 0
}
if isCJK {
word = tpl.StripHTML(word)
runeCount := utf8.RuneCountInString(word)
@@ -193,7 +211,7 @@ func ExtractSummaryFromHTML(mt media.Type, input string, numWords int, isCJK boo
for j := result.WrapperStart.High; j < high; {
s := input[j:]
closingIndex := strings.Index(s, "</"+ptag.tagName)
closingIndex := strings.Index(s, "</"+ptag.tagName+">")
if closingIndex == -1 {
break
+13 -1
View File
@@ -171,7 +171,7 @@ includecontent: {{ hugo.Context.MarkupScope }}|{{ $p.Markup.Render.Content }}|
)
}
func TestPageMarkupWithoutSummary(t *testing.T) {
func TestPageContentWithoutSummary(t *testing.T) {
t.Parallel()
files := `
@@ -195,6 +195,13 @@ This is some content about a summary and more.
Another paragraph.
Third paragraph.
-- content/p3.md --
---
title: "Post 3"
date: "2020-01-01"
summary: "This is summary in front matter."
---
This is content.
-- layouts/_default/single.html --
Single.
Page.Summary: {{ .Summary }}|
@@ -229,6 +236,11 @@ Summary Truncated: {{ .Truncated }}|
"Summary Type: auto",
"Summary Truncated: true",
)
b.AssertFileContentExact("public/p3/index.html",
"Summary: This is summary in front matter.|",
"ContentWithoutSummary: <p>This is content.</p>\n|",
)
}
func TestPageMarkupWithoutSummaryRST(t *testing.T) {
+57
View File
@@ -49,6 +49,46 @@ func TestExtractSummaryFromHTML(t *testing.T) {
}
}
// See https://discourse.gohugo.io/t/automatic-summarys-summarylength-seems-broken-in-the-case-of-plainify/51466/4
// Also issue 12837
func TestExtractSummaryFromHTMLLotsOfHTMLInSummary(t *testing.T) {
c := qt.New(t)
input := `
<p>
<div>
<picture>
<img src="imgs/1.jpg" alt="1"/>
</picture>
<picture>
<img src="imgs/2.jpg" alt="2"/>
</picture>
<picture>
<img src="imgs/3.jpg" alt="3"/>
</picture>
<picture>
<img src="imgs/4.jpg" alt="4"/>
</picture>
<picture>
<img src="imgs/5.jpg" alt="5"/>
</picture>
</div>
</p>
<p>
This is a story about a cat.
</p>
<p>
The cat was white and fluffy.
</p>
<p>
And it liked milk.
</p>
`
summary := ExtractSummaryFromHTML(media.Builtin.MarkdownType, input, 10, false)
c.Assert(strings.HasSuffix(summary.Summary(), "<p>\nThis is a story about a cat.\n</p>\n<p>\nThe cat was white and fluffy.\n</p>"), qt.IsTrue)
}
func TestExtractSummaryFromHTMLWithDivider(t *testing.T) {
c := qt.New(t)
@@ -114,6 +154,23 @@ func TestExpandDivider(t *testing.T) {
}
}
func TestIsProbablyHTMLToken(t *testing.T) {
c := qt.New(t)
for i, test := range []struct {
input string
expect bool
}{
{"<p>", true},
{"<p", true},
{"width=\"32\"", true},
{"width='32'", true},
{"<p>Æøå", false},
} {
c.Assert(isProbablyHTMLToken(test.input), qt.Equals, test.expect, qt.Commentf("[%d] Test.expect %q", i, test.input))
}
}
func BenchmarkSummaryFromHTML(b *testing.B) {
b.StopTimer()
input := "<p>First paragraph</p><p>Second paragraph</p>"