Compare commits

..

1 Commits

Author SHA1 Message Date
Bjørn Erik Pedersen 10ddc2ef92 Improve error messages for PostCSS etc.
Fixes #9730
2023-07-17 19:42:13 +02:00
262 changed files with 2095 additions and 2902 deletions
+1 -1
View File
@@ -1,4 +1,4 @@
[bep]: https://github.com/bep
[bep]: https://github.com/spf13
[bugs]: https://github.com/gohugoio/hugo/issues?q=is%3Aopen+is%3Aissue+label%3ABug
[contributing]: CONTRIBUTING.md
[create a proposal]: https://github.com/gohugoio/hugo/issues/new?labels=Proposal%2C+NeedsTriage&template=feature_request.md
+1 -1
View File
@@ -515,7 +515,7 @@ Complete documentation is available at https://gohugo.io/.`
func applyLocalFlagsBuildConfig(cmd *cobra.Command, r *rootCommand) {
cmd.Flags().StringSliceP("theme", "t", []string{}, "themes to use (located in /themes/THEMENAME/)")
cmd.Flags().StringVarP(&r.baseURL, "baseURL", "b", "", "hostname (and path) to the root, e.g. https://spf13.com/")
cmd.Flags().StringP("cacheDir", "", "", "filesystem path to cache directory")
cmd.Flags().StringP("cacheDir", "", "", "filesystem path to cache directory. Defaults: $TMPDIR/hugo_cache_$USER/")
_ = cmd.Flags().SetAnnotation("cacheDir", cobra.BashCompSubdirsInDir, []string{})
cmd.Flags().StringP("contentDir", "c", "", "filesystem path to content directory")
_ = cmd.Flags().SetAnnotation("theme", cobra.BashCompSubdirsInDir, []string{"themes"})
+7 -6
View File
@@ -86,12 +86,13 @@ func flagsToCfgWithAdditionalConfigBase(cd *simplecobra.Commandeer, cfg config.P
// Flags that we for some reason don't want to expose in the site config.
internalKeySet := map[string]bool{
"quiet": true,
"verbose": true,
"watch": true,
"liveReloadPort": true,
"renderToMemory": true,
"clock": true,
"quiet": true,
"verbose": true,
"watch": true,
"disableLiveReload": true,
"liveReloadPort": true,
"renderToMemory": true,
"clock": true,
}
cmd := cd.CobraCommand
+1 -1
View File
@@ -348,7 +348,7 @@ description = ""
homepage = "http://example.com/"
tags = []
features = []
min_version = "0.116.0"
min_version = "0.115.0"
[author]
name = ""
+11 -11
View File
@@ -23,6 +23,7 @@ import (
"errors"
"fmt"
"io"
"io/ioutil"
"net"
"net/http"
"net/url"
@@ -469,6 +470,14 @@ func (c *serverCommand) Name() string {
}
func (c *serverCommand) Run(ctx context.Context, cd *simplecobra.Commandeer, args []string) error {
err := func() error {
defer c.r.timeTrack(time.Now(), "Built")
err := c.build()
return err
}()
if err != nil {
return err
}
// Watch runs its own server as part of the routine
if c.serverWatch {
@@ -492,15 +501,6 @@ func (c *serverCommand) Run(ctx context.Context, cd *simplecobra.Commandeer, arg
}
err := func() error {
defer c.r.timeTrack(time.Now(), "Built")
err := c.build()
return err
}()
if err != nil {
return err
}
return c.serve()
}
@@ -685,9 +685,9 @@ func (c *serverCommand) createCertificates(conf *commonConfig) error {
c.tlsKeyFile = filepath.Join(keyDir, fmt.Sprintf("%s-key.pem", hostname))
// Check if the certificate already exists and is valid.
certPEM, err := os.ReadFile(c.tlsCertFile)
certPEM, err := ioutil.ReadFile(c.tlsCertFile)
if err == nil {
rootPem, err := os.ReadFile(filepath.Join(mclib.GetCAROOT(), "rootCA.pem"))
rootPem, err := ioutil.ReadFile(filepath.Join(mclib.GetCAROOT(), "rootCA.pem"))
if err == nil {
if err := c.verifyCert(rootPem, certPEM, hostname); err == nil {
c.r.Println("Using existing", c.tlsCertFile, "and", c.tlsKeyFile)
-44
View File
@@ -15,9 +15,7 @@ package hstrings
import (
"fmt"
"regexp"
"strings"
"sync"
"github.com/gohugoio/hugo/compare"
)
@@ -57,45 +55,3 @@ func EqualAny(a string, b ...string) bool {
}
return false
}
// regexpCache represents a cache of regexp objects protected by a mutex.
type regexpCache struct {
mu sync.RWMutex
re map[string]*regexp.Regexp
}
func (rc *regexpCache) getOrCompileRegexp(pattern string) (re *regexp.Regexp, err error) {
var ok bool
if re, ok = rc.get(pattern); !ok {
re, err = regexp.Compile(pattern)
if err != nil {
return nil, err
}
rc.set(pattern, re)
}
return re, nil
}
func (rc *regexpCache) get(key string) (re *regexp.Regexp, ok bool) {
rc.mu.RLock()
re, ok = rc.re[key]
rc.mu.RUnlock()
return
}
func (rc *regexpCache) set(key string, re *regexp.Regexp) {
rc.mu.Lock()
rc.re[key] = re
rc.mu.Unlock()
}
var reCache = regexpCache{re: make(map[string]*regexp.Regexp)}
// GetOrCompileRegexp retrieves a regexp object from the cache based upon the pattern.
// If the pattern is not found in the cache, the pattern is compiled and added to
// the cache.
func GetOrCompileRegexp(pattern string) (re *regexp.Regexp, err error) {
return reCache.getOrCompileRegexp(pattern)
}
-22
View File
@@ -14,7 +14,6 @@
package hstrings
import (
"regexp"
"testing"
qt "github.com/frankban/quicktest"
@@ -35,24 +34,3 @@ func TestStringEqualFold(t *testing.T) {
c.Assert(StringEqualFold(s1).Eq("b"), qt.Equals, false)
}
func TestGetOrCompileRegexp(t *testing.T) {
c := qt.New(t)
re, err := GetOrCompileRegexp(`\d+`)
c.Assert(err, qt.IsNil)
c.Assert(re.MatchString("123"), qt.Equals, true)
}
func BenchmarkGetOrCompileRegexp(b *testing.B) {
for i := 0; i < b.N; i++ {
GetOrCompileRegexp(`\d+`)
}
}
func BenchmarkCompileRegexp(b *testing.B) {
for i := 0; i < b.N; i++ {
regexp.MustCompile(`\d+`)
}
}
-83
View File
@@ -1,83 +0,0 @@
// Copyright 2022 The Hugo Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package htime_test
import (
"testing"
"github.com/gohugoio/hugo/hugolib"
)
// Issue #11267
func TestApplyWithContext(t *testing.T) {
t.Parallel()
files := `
-- config.toml --
defaultContentLanguage = 'it'
-- layouts/index.html --
{{ $dates := slice
"2022-01-03"
"2022-02-01"
"2022-03-02"
"2022-04-07"
"2022-05-06"
"2022-06-04"
"2022-07-03"
"2022-08-01"
"2022-09-06"
"2022-10-05"
"2022-11-03"
"2022-12-02"
}}
{{ range $dates }}
{{ . | time.Format "month: _January_ weekday: _Monday_" }}
{{ . | time.Format "month: _Jan_ weekday: _Mon_" }}
{{ end }}
`
b := hugolib.NewIntegrationTestBuilder(
hugolib.IntegrationTestConfig{
T: t,
TxtarString: files,
},
).Build()
b.AssertFileContent("public/index.html", `
month: _gennaio_ weekday: _lunedì_
month: _gen_ weekday: _lun_
month: _febbraio_ weekday: _martedì_
month: _feb_ weekday: _mar_
month: _marzo_ weekday: _mercoledì_
month: _mar_ weekday: _mer_
month: _aprile_ weekday: _giovedì_
month: _apr_ weekday: _gio_
month: _maggio_ weekday: _venerdì_
month: _mag_ weekday: _ven_
month: _giugno_ weekday: _sabato_
month: _giu_ weekday: _sab_
month: _luglio_ weekday: _domenica_
month: _lug_ weekday: _dom_
month: _agosto_ weekday: _lunedì_
month: _ago_ weekday: _lun_
month: _settembre_ weekday: _martedì_
month: _set_ weekday: _mar_
month: _ottobre_ weekday: _mercoledì_
month: _ott_ weekday: _mer_
month: _novembre_ weekday: _giovedì_
month: _nov_ weekday: _gio_
month: _dicembre_ weekday: _venerdì_
month: _dic_ weekday: _ven_
`)
}
+4 -7
View File
@@ -124,15 +124,12 @@ func (f TimeFormatter) Format(t time.Time, layout string) string {
monthIdx := t.Month() - 1 // Month() starts at 1.
dayIdx := t.Weekday()
if strings.Contains(layout, "January") {
s = strings.ReplaceAll(s, longMonthNames[monthIdx], f.ltr.MonthWide(t.Month()))
} else if strings.Contains(layout, "Jan") {
s = strings.ReplaceAll(s, longMonthNames[monthIdx], f.ltr.MonthWide(t.Month()))
if !strings.Contains(s, f.ltr.MonthWide(t.Month())) {
s = strings.ReplaceAll(s, shortMonthNames[monthIdx], f.ltr.MonthAbbreviated(t.Month()))
}
if strings.Contains(layout, "Monday") {
s = strings.ReplaceAll(s, longDayNames[dayIdx], f.ltr.WeekdayWide(t.Weekday()))
} else if strings.Contains(layout, "Mon") {
s = strings.ReplaceAll(s, longDayNames[dayIdx], f.ltr.WeekdayWide(t.Weekday()))
if !strings.Contains(s, f.ltr.WeekdayWide(t.Weekday())) {
s = strings.ReplaceAll(s, shortDayNames[dayIdx], f.ltr.WeekdayAbbreviated(t.Weekday()))
}
+1 -1
View File
@@ -19,5 +19,5 @@ var CurrentVersion = Version{
Major: 0,
Minor: 116,
PatchLevel: 0,
Suffix: "",
Suffix: "-DEV",
}
-10
View File
@@ -173,7 +173,6 @@ type Logger interface {
WarnCommand(command string) logg.LevelLogger
Warnf(format string, v ...any)
Warnln(v ...any)
Deprecatef(fail bool, format string, v ...any)
}
type logAdapter struct {
@@ -298,15 +297,6 @@ func (l *logAdapter) sprint(v ...any) string {
return strings.TrimRight(fmt.Sprintln(v...), "\n")
}
func (l *logAdapter) Deprecatef(fail bool, format string, v ...any) {
format = "DEPRECATED: " + format
if fail {
l.errorl.Logf(format, v...)
} else {
l.warnl.Logf(format, v...)
}
}
type logWriter struct {
l logg.LevelLogger
}
+17 -38
View File
@@ -45,7 +45,6 @@ import (
"github.com/gohugoio/hugo/output"
"github.com/gohugoio/hugo/related"
"github.com/gohugoio/hugo/resources/images"
"github.com/gohugoio/hugo/resources/kinds"
"github.com/gohugoio/hugo/resources/page"
"github.com/gohugoio/hugo/resources/page/pagemeta"
"github.com/spf13/afero"
@@ -58,11 +57,12 @@ type InternalConfig struct {
// Server mode?
Running bool
Quiet bool
Verbose bool
Clock string
Watch bool
LiveReloadPort int
Quiet bool
Verbose bool
Clock string
Watch bool
DisableLiveReload bool
LiveReloadPort int
}
// All non-params config keys for language.
@@ -240,14 +240,9 @@ func (c *Config) CompileConfig(logger loggers.Logger) error {
disabledKinds := make(map[string]bool)
for _, kind := range c.DisableKinds {
kind = strings.ToLower(kind)
if newKind := kinds.IsDeprecatedAndReplacedWith(kind); newKind != "" {
logger.Deprecatef(false, "Kind %q used in disableKinds is deprecated, use %q instead.", kind, newKind)
if kind == "taxonomyterm" {
// Legacy config.
kind = newKind
}
if kinds.GetKindAny(kind) == "" {
logger.Warnf("Unknown kind %q in disableKinds configuration.", kind)
continue
kind = "term"
}
disabledKinds[kind] = true
}
@@ -255,17 +250,9 @@ func (c *Config) CompileConfig(logger loggers.Logger) error {
isRssDisabled := disabledKinds["rss"]
outputFormats := c.OutputFormats.Config
for kind, formats := range c.Outputs {
if newKind := kinds.IsDeprecatedAndReplacedWith(kind); newKind != "" {
logger.Deprecatef(false, "Kind %q used in outputs configuration is deprecated, use %q instead.", kind, newKind)
kind = newKind
}
if disabledKinds[kind] {
continue
}
if kinds.GetKindAny(kind) == "" {
logger.Warnf("Unknown kind %q in outputs configuration.", kind)
continue
}
for _, format := range formats {
if isRssDisabled && format == "rss" {
// Legacy config.
@@ -467,9 +454,6 @@ type RootConfig struct {
// Disable the injection of the Hugo generator tag on the home page.
DisableHugoGeneratorInject bool
// Disable live reloading in server mode.
DisableLiveReload bool
// Enable replacement in Pages' Content of Emoji shortcodes with their equivalent Unicode characters.
// <docsmeta>{"identifiers": ["Content", "Unicode"] }</docsmeta>
EnableEmoji bool
@@ -743,8 +727,7 @@ func fromLoadConfigResult(fs afero.Fs, logger loggers.Logger, res config.LoadCon
cfg := res.Cfg
all := &Config{}
err := decodeConfigFromParams(fs, logger, bcfg, cfg, all, nil)
err := decodeConfigFromParams(fs, bcfg, cfg, all, nil)
if err != nil {
return nil, err
}
@@ -832,7 +815,7 @@ func fromLoadConfigResult(fs afero.Fs, logger loggers.Logger, res config.LoadCon
// Create a copy of the complete config and replace the root keys with the language specific ones.
clone := all.cloneForLang()
if err := decodeConfigFromParams(fs, logger, bcfg, mergedConfig, clone, differentRootKeys); err != nil {
if err := decodeConfigFromParams(fs, bcfg, mergedConfig, clone, differentRootKeys); err != nil {
return nil, fmt.Errorf("failed to decode config for language %q: %w", k, err)
}
if err := clone.CompileConfig(logger); err != nil {
@@ -886,10 +869,6 @@ func fromLoadConfigResult(fs afero.Fs, logger loggers.Logger, res config.LoadCon
bcfg.PublishDir = all.PublishDir
res.BaseConfig = bcfg
all.CommonDirs.CacheDir = bcfg.CacheDir
for _, l := range langConfigs {
l.CommonDirs.CacheDir = bcfg.CacheDir
}
cm := &Configs{
Base: all,
@@ -904,7 +883,7 @@ func fromLoadConfigResult(fs afero.Fs, logger loggers.Logger, res config.LoadCon
return cm, nil
}
func decodeConfigFromParams(fs afero.Fs, logger loggers.Logger, bcfg config.BaseConfig, p config.Provider, target *Config, keys []string) error {
func decodeConfigFromParams(fs afero.Fs, bcfg config.BaseConfig, p config.Provider, target *Config, keys []string) error {
var decoderSetups []decodeWeight
@@ -917,7 +896,7 @@ func decodeConfigFromParams(fs afero.Fs, logger loggers.Logger, bcfg config.Base
if v, found := allDecoderSetups[key]; found {
decoderSetups = append(decoderSetups, v)
} else {
logger.Warnf("Skip unknown config key %q", key)
return fmt.Errorf("unknown config key %q", key)
}
}
}
@@ -954,11 +933,11 @@ func createDefaultOutputFormats(allFormats output.Formats) map[string][]string {
}
m := map[string][]string{
kinds.KindPage: {htmlOut.Name},
kinds.KindHome: defaultListTypes,
kinds.KindSection: defaultListTypes,
kinds.KindTerm: defaultListTypes,
kinds.KindTaxonomy: defaultListTypes,
page.KindPage: {htmlOut.Name},
page.KindHome: defaultListTypes,
page.KindSection: defaultListTypes,
page.KindTerm: defaultListTypes,
page.KindTaxonomy: defaultListTypes,
}
// May be disabled
+5 -25
View File
@@ -297,20 +297,14 @@ func (l configLoader) applyOsEnvOverrides(environ []string) error {
if nestedKey != "" {
owner[nestedKey] = env.Value
} else {
var val any
key := strings.ReplaceAll(env.Key, delim, ".")
_, ok := allDecoderSetups[key]
if ok {
var val any = env.Value
if _, ok := allDecoderSetups[env.Key]; ok {
// A map.
if v, err := metadecoders.Default.UnmarshalStringTo(env.Value, map[string]interface{}{}); err == nil {
val = v
}
val, err = metadecoders.Default.UnmarshalStringTo(env.Value, map[string]interface{}{})
}
if val == nil {
// A string.
val = l.envStringToVal(key, env.Value)
if err == nil {
l.cfg.Set(strings.ReplaceAll(env.Key, delim, "."), val)
}
l.cfg.Set(key, val)
}
}
}
@@ -318,20 +312,6 @@ func (l configLoader) applyOsEnvOverrides(environ []string) error {
return nil
}
func (l *configLoader) envStringToVal(k, v string) any {
switch k {
case "disablekinds", "disablelanguages":
if strings.Contains(v, ",") {
return strings.Split(v, ",")
} else {
return strings.Fields(v)
}
default:
return v
}
}
func (l *configLoader) loadConfigMain(d ConfigSourceDescriptor) (config.LoadConfigResult, modules.ModulesConfig, error) {
var res config.LoadConfigResult
+8 -8
View File
@@ -333,11 +333,11 @@ func (c *CacheBuster) CompileConfig(logger loggers.Logger) error {
}
source := c.Source
target := c.Target
sourceRe, err := regexp.Compile(source)
if err != nil {
return fmt.Errorf("failed to compile cache buster source %q: %w", c.Source, err)
}
target := c.Target
var compileErr error
debugl := logger.Logger().WithLevel(logg.LevelDebug).WithField(loggers.FieldNameCmd, "cachebuster")
@@ -353,23 +353,23 @@ func (c *CacheBuster) CompileConfig(logger loggers.Logger) error {
return nil
}
groups := m[1:]
currentTarget := target
// Replace $1, $2 etc. in target.
for i, g := range groups {
currentTarget = strings.ReplaceAll(target, fmt.Sprintf("$%d", i+1), g)
target = strings.ReplaceAll(target, fmt.Sprintf("$%d", i+1), g)
}
targetRe, err := regexp.Compile(currentTarget)
targetRe, err := regexp.Compile(target)
if err != nil {
compileErr = fmt.Errorf("failed to compile cache buster target %q: %w", currentTarget, err)
compileErr = fmt.Errorf("failed to compile cache buster target %q: %w", target, err)
return nil
}
return func(ss string) bool {
match = targetRe.MatchString(ss)
return func(s string) bool {
match = targetRe.MatchString(s)
matchString := "no match"
if match {
matchString = "match!"
}
logger.Debugf("Matching %q with target %q: %s", ss, currentTarget, matchString)
logger.Debugf("Matching %q with target %q: %s", s, target, matchString)
return match
}
-33
View File
@@ -164,36 +164,3 @@ func TestBuildConfigCacheBusters(t *testing.T) {
c.Assert(m("json"), qt.IsTrue)
}
func TestBuildConfigCacheBusterstTailwindSetup(t *testing.T) {
c := qt.New(t)
cfg := New()
cfg.Set("build", map[string]interface{}{
"cacheBusters": []map[string]string{
{
"source": "assets/watching/hugo_stats\\.json",
"target": "css",
},
{
"source": "(postcss|tailwind)\\.config\\.js",
"target": "css",
},
{
"source": "assets/.*\\.(js|ts|jsx|tsx)",
"target": "js",
},
{
"source": "assets/.*\\.(.*)$",
"target": "$1",
},
},
})
conf := DecodeBuildConfig(cfg)
l := loggers.NewDefault()
c.Assert(conf.CompileConfig(l), qt.IsNil)
m, err := conf.MatchCacheBuster(l, "assets/watching/hugo_stats.json")
c.Assert(err, qt.IsNil)
c.Assert(m("css"), qt.IsTrue)
}
+1 -1
View File
@@ -1,3 +1,3 @@
### Asking support questions
### Asking Support Questions
We have an active [discussion forum](https://discourse.gohugo.io) where users and developers can ask questions. Please don't use the GitHub issue tracker to ask questions.
File diff suppressed because one or more lines are too long

Before

Width:  |  Height:  |  Size: 9.3 KiB

After

Width:  |  Height:  |  Size: 3.5 KiB

File diff suppressed because one or more lines are too long

Before

Width:  |  Height:  |  Size: 13 KiB

File diff suppressed because one or more lines are too long

Before

Width:  |  Height:  |  Size: 13 KiB

@@ -3,20 +3,19 @@
link = "https://www.linode.com/"
logo = "images/sponsors/linode-logo.svg"
utm_campaign = "hugosponsor"
bgcolor = "#ffffff"
[[banners]]
name = "CloudCannon"
link = "https://cloudcannon.com/hugo-cms/"
logo = "/images/sponsors/cloudcannon-white.svg"
utm_campaign = "HugoSponsorship"
utm_source = "sponsor"
utm_content = "gohugo"
bgcolor = "#034AD8"
[[banners]]
name = "Your Company?"
link = "https://bep.is/en/hugo-sponsor-2023-01/"
logo = "/images/sponsors/your-company.svg"
utm_campaign = "hugosponsor"
show_on_hover = true
bgcolor = "#4e4f4f"
bgcolor = "#004887"
[[banners]]
name = "Your Company?"
link = "https://bep.is/en/hugo-sponsor-2023-01/"
logo = "/images/sponsors/your-company.svg"
utm_campaign = "hugosponsor"
show_on_hover = true
bgcolor = "#004887"
@@ -23,7 +23,7 @@
class="{{ $classes_box }} o-100"
style="background-color: {{ .bgcolor }};">
{{ $query_params := .query_params | default "" }}
{{ $url := printf "%s?%s%s" .link $query_params (querify "utm_source" (.utm_source | default $utmSource ) "utm_medium" "banner" "utm_campaign" (.utm_campaign | default "hugosponsor") "utm_content" (.utm_content | default "gohugoio")) | safeURL }}
{{ $url := printf "%s?%s%s" .link $query_params (querify "utm_source" $utmSource "utm_medium" "banner" "utm_campaign" (.utm_campaign | default "hugosponsor")) | safeURL }}
{{ $logo := resources.Get .logo }}
{{ if hugo.IsProduction }}
{{ $gtagID := printf "Sponsor %s %s" .name $gtag | title }}
@@ -34,7 +34,7 @@
show-on-hover
{{ end }}"
style="">
{{ with $logo }}{{ .Content | safeHTML }}{{ end }}
{{ $logo.Content | safeHTML }}
</a>
{{ else }}
<a
@@ -42,7 +42,7 @@
class="w-100 grow pa3{{ if .show_on_hover }}
show-on-hover
{{ end }}">
{{ with $logo }}{{ .Content | safeHTML }}{{ end }}
{{ $logo.Content | safeHTML }}
</a>
{{ end }}
</div>
+1 -1
View File
@@ -1 +1 @@
# github.com/gohugoio/gohugoioTheme v0.0.0-20230630055807-9874cd863bc5
# github.com/gohugoio/gohugoioTheme v0.0.0-20230527124826-78bc315d7b8a
+6 -6
View File
@@ -11,7 +11,7 @@
url = "/installation/"
[[docs]]
name = "Getting started"
name = "Getting Started"
weight = 30
identifier = "getting-started"
url = "/getting-started/"
@@ -26,7 +26,7 @@
# Core menus
[[docs]]
name = "Content management"
name = "Content Management"
weight = 50
identifier = "content-management"
post = "expanded"
@@ -53,7 +53,7 @@
[[docs]]
name = "Hugo Pipes"
weight = 90
identifier = "hugo-pipes"
identifier = "pipes"
url = "/hugo-pipes/"
[[docs]]
@@ -72,13 +72,13 @@
url = "/troubleshooting/"
[[docs]]
name = "Developer tools"
name = "Tools"
weight = 120
identifier = "developer-tools"
identifier = "tools"
url = "/tools/"
[[docs]]
name = "Hosting and deployment"
name = "Hosting & Deployment"
weight = 130
identifier = "hosting-and-deployment"
url = "/hosting-and-deployment/"
+1 -1
View File
@@ -1,5 +1,5 @@
---
title: The worlds fastest framework for building websites
title: "The worlds fastest framework for building websites"
date: 2017-03-02T12:00:00-05:00
features:
- heading: Blistering Speed
+3 -4
View File
@@ -1,15 +1,14 @@
---
title: About Hugo
linkTitle: Overview
linktitle: Overview
description: Hugo's features, roadmap, license, and motivation.
categories: []
keywords: []
menu:
docs:
identifier: about-hugo-overview
parent: about
weight: 10
weight: 10
weight: 1
weight: 1
aliases: [/about-hugo/,/docs/]
---
+5 -5
View File
@@ -1,13 +1,13 @@
---
title: Benefits of static site generators
linkTitle: Static site generators
title: The Benefits of Static Site Generators
linktitle: The Benefits of Static
description: Improved performance, security and ease of use are just a few of the reasons static site generators are so appealing.
keywords: [ssg,static,performance,security]
menu:
docs:
parent: about
weight: 40
weight: 40
weight: 30
weight: 30
---
The purpose of website generators is to render content into HTML files. Most are "dynamic site generators." That means the HTTP server---i.e., the program that sends files to the browser to be viewed---runs the generator to create a new HTML file every time an end user requests a page.
@@ -18,7 +18,7 @@ Hugo takes caching a step further and all HTML files are rendered on your comput
This has many benefits. The most noticeable is performance. HTTP servers are *very* good at sending files---so good, in fact, that you can effectively serve the same number of pages with a fraction of the memory and CPU needed for a dynamic site.
## More on static site generators
## More on Static Site Generators
* ["An Introduction to Static Site Generators", David Walsh]
* ["Hugo vs. WordPress page load speed comparison: Hugo leaves WordPress in its dust", GettingThingsTech][hugovwordpress]
+4 -4
View File
@@ -1,11 +1,11 @@
---
title: Hugo features
title: Hugo Features
description: Hugo boasts blistering speed, robust content management, and a powerful templating language making it a great fit for all kinds of static websites.
menu:
docs:
parent: about
weight: 30
weight: 30
weight: 20
weight: 20
toc: true
---
@@ -40,7 +40,7 @@ toc: true
* ["Minutes to Read"][pagevars] functionality
* ["WordCount"][pagevars] functionality
## Additional features
## Additional Features
* Integrated [Disqus] comment support
* Integrated [Google Analytics] support
+11 -11
View File
@@ -1,14 +1,14 @@
---
title: Hugo and the General Data Protection Regulation
linkTitle: Hugo and the GDPR
title: Hugo and the General Data Protection Regulation (GDPR)
linktitle: Hugo and GDPR
description: About how to configure your Hugo site to meet the new regulations.
layout: single
keywords: ["GDPR", "Privacy", "Data Protection"]
menu:
docs:
parent: about
weight: 60
weight: 60
weight: 5
weight: 5
aliases: [/privacy/,/gdpr/]
toc: true
---
@@ -17,7 +17,7 @@ toc: true
**Hugo is a static site generator. By using Hugo you are already standing on very solid ground. Static HTML files on disk are much easier to reason about compared to server and database driven web sites.**
But even static websites can integrate with external services, so from version `0.41`, Hugo provides a **privacy configuration** that covers the relevant built-in templates.
But even static websites can integrate with external services, so from version `0.41`, Hugo provides a **Privacy Config** that covers the relevant built-in templates.
Note that:
@@ -25,9 +25,9 @@ toc: true
* These settings work with the [internal templates](/templates/internal/). Some theme may contain custom templates for embedding services like Google Analytics. In that case these options have no effect.
* We will continue this work and improve this further in future Hugo versions.
## All privacy settings
## All Privacy Settings
Below are all privacy settings and their default value. These settings need to be put in your site configuration (e.g. `hugo.toml`).
Below are all privacy settings and their default value. These settings need to be put in your site config (e.g. `hugo.toml`).
{{< code-toggle file="hugo" >}}
[privacy]
@@ -54,11 +54,11 @@ disable = false
privacyEnhanced = false
{{< /code-toggle >}}
## Disable all services
## Disable All Services
An example privacy configuration that disables all the relevant services in Hugo. With this configuration, the other settings will not matter.
An example Privacy Config that disables all the relevant services in Hugo. With this configuration, the other settings will not matter.
{{< code-toggle file="hugo" >}}
{{< code-toggle file="hugo" >}}
[privacy]
[privacy.disqus]
disable = true
@@ -74,7 +74,7 @@ disable = true
disable = true
{{< /code-toggle >}}
## The privacy settings explained
## The Privacy Settings Explained
### GoogleAnalytics
+4 -3
View File
@@ -1,13 +1,14 @@
---
title: License
title: Apache License
linktitle: License
description: Hugo v0.15 and later are released under the Apache 2.0 license.
categories: ["about hugo"]
keywords: ["License","apache"]
menu:
docs:
parent: about
weight: 70
weight: 70
weight: 60
weight: 60
aliases: [/meta/license]
toc: true
---
@@ -1,18 +1,18 @@
---
title: Hugo's security model
title: Hugo's Security Model
description: A summary of Hugo's security model.
layout: single
keywords: ["Security", "Privacy"]
menu:
docs:
parent: about
weight: 50
weight: 50
weight: 4
weight: 5
aliases: [/security/]
toc: true
---
## Runtime security
## Runtime Security
Hugo produces static output, so once built, the runtime is the browser (assuming the output is HTML) and any server (API) that you integrate with.
@@ -25,7 +25,7 @@ But when developing and building your site, the runtime is the `hugo` executable
* User-defined components have read-only access to the filesystem.
* We shell out to some external binaries to support [Asciidoctor](/content-management/formats/#list-of-content-formats) and similar, but those binaries and their flags are predefined and disabled by default (see [Security Policy](#security-policy)). General functions to run arbitrary external OS commands have been [discussed](https://github.com/gohugoio/hugo/issues/796), but not implemented because of security concerns.
## Security policy
## Security Policy
Hugo has a built-in security policy that restricts access to [os/exec](https://pkg.go.dev/os/exec), remote communication and similar.
@@ -33,19 +33,19 @@ The default configuration is listed below. Any build using features not in the a
{{< code-toggle config="security" />}}
Note that these and other configuration settings in Hugo can be overridden by the OS environment. If you want to block all remote HTTP fetching of data:
Note that these and other config settings in Hugo can be overridden by the OS environment. If you want to block all remote HTTP fetching of data:
```txt
HUGO_SECURITY_HTTP_URLS=none hugo
```
## Dependency security
## Dependency Security
Hugo is built as a static binary using [Go Modules](https://github.com/golang/go/wiki/Modules) to manage its dependencies. Go Modules have several safeguards, one of them being the `go.sum` file. This is a database of the expected cryptographic checksums of all of your dependencies, including transitive dependencies.
[Hugo Modules](/hugo-modules/) is a feature built on top of the functionality of Go Modules. Like Go Modules, a Hugo project using Hugo Modules will have a `go.sum` file. We recommend that you commit this file to your version control system. The Hugo build will fail if there is a checksum mismatch, which would be an indication of [dependency tampering](https://julienrenaux.fr/2019/12/20/github-actions-security-risk/).
## Web application security
## Web Application Security
These are the security threats as defined by [OWASP](https://en.wikipedia.org/wiki/OWASP).
+5 -5
View File
@@ -5,8 +5,8 @@ layout: single
menu:
docs:
parent: about
weight: 20
weight: 20
weight: 10
weight: 10
aliases: [/overview/introduction/,/about/why-i-built-hugo/]
toc: true
---
@@ -17,15 +17,15 @@ Websites built with Hugo are extremely fast and secure. Hugo sites can be hosted
We think of Hugo as the ideal website creation tool with nearly instant build times, able to rebuild whenever a change is made.
## How fast is Hugo?
## How Fast is Hugo?
{{< youtube "CdiDYZ51a2o" >}}
## What does Hugo do?
## What Does Hugo Do?
In technical terms, Hugo takes a source directory of files and templates and uses these as input to create a complete website.
## Who should use Hugo?
## Who Should Use Hugo?
Hugo is for people that prefer writing in a text editor over a browser.
+1 -1
View File
@@ -27,7 +27,7 @@ hugo [flags]
-D, --buildDrafts include content marked as draft
-E, --buildExpired include expired content
-F, --buildFuture include content with publishdate in the future
--cacheDir string filesystem path to cache directory
--cacheDir string filesystem path to cache directory. Defaults: $TMPDIR/hugo_cache_$USER/
--cleanDestinationDir remove files from destination not found in static directories
--clock string set the clock used by Hugo, e.g. --clock 2021-11-06T22:30:00.00+09:00
--config string config file (default is hugo.yaml|json|toml)
+1 -1
View File
@@ -19,7 +19,7 @@ hugo config [command] [flags]
```
-b, --baseURL string hostname (and path) to the root, e.g. https://spf13.com/
--cacheDir string filesystem path to cache directory
--cacheDir string filesystem path to cache directory. Defaults: $TMPDIR/hugo_cache_$USER/
-c, --contentDir string filesystem path to content directory
--format string preferred file format (toml, yaml or json) (default "toml")
-h, --help help for config
@@ -15,7 +15,7 @@ hugo config mounts [flags] [args]
```
-b, --baseURL string hostname (and path) to the root, e.g. https://spf13.com/
--cacheDir string filesystem path to cache directory
--cacheDir string filesystem path to cache directory. Defaults: $TMPDIR/hugo_cache_$USER/
-c, --contentDir string filesystem path to content directory
-h, --help help for mounts
-t, --theme strings themes to use (located in /themes/THEMENAME/)
+4
View File
@@ -13,6 +13,10 @@ Convert your content (e.g. front matter) to different formats.
See convert's subcommands toJSON, toTOML and toYAML for more information.
```
hugo convert [command] [flags]
```
### Options
```
+4
View File
@@ -7,6 +7,10 @@ url: /commands/hugo_gen/
A collection of several useful generators.
```
hugo gen [command] [flags]
```
### Options
```
+4
View File
@@ -13,6 +13,10 @@ Import your site from other web site generators like Jekyll.
Import requires a subcommand, e.g. `hugo import jekyll jekyll_root_path target_path`.
```
hugo import [command] [flags]
```
### Options
```
+4
View File
@@ -13,6 +13,10 @@ Listing out various types of content.
List requires a subcommand, e.g. hugo list drafts
```
hugo list [command] [flags]
```
### Options
```
+1 -1
View File
@@ -20,7 +20,7 @@ hugo mod clean [flags] [args]
```
--all clean entire module cache
-b, --baseURL string hostname (and path) to the root, e.g. https://spf13.com/
--cacheDir string filesystem path to cache directory
--cacheDir string filesystem path to cache directory. Defaults: $TMPDIR/hugo_cache_$USER/
-c, --contentDir string filesystem path to content directory
-h, --help help for clean
--pattern string pattern matching module paths to clean (all if not set), e.g. "**hugo*"
+1 -1
View File
@@ -21,7 +21,7 @@ hugo mod graph [flags] [args]
```
-b, --baseURL string hostname (and path) to the root, e.g. https://spf13.com/
--cacheDir string filesystem path to cache directory
--cacheDir string filesystem path to cache directory. Defaults: $TMPDIR/hugo_cache_$USER/
--clean delete module cache for dependencies that fail verification
-c, --contentDir string filesystem path to content directory
-h, --help help for graph
+1 -1
View File
@@ -26,7 +26,7 @@ hugo mod init [flags] [args]
```
-b, --baseURL string hostname (and path) to the root, e.g. https://spf13.com/
--cacheDir string filesystem path to cache directory
--cacheDir string filesystem path to cache directory. Defaults: $TMPDIR/hugo_cache_$USER/
-c, --contentDir string filesystem path to content directory
-h, --help help for init
-t, --theme strings themes to use (located in /themes/THEMENAME/)
@@ -29,7 +29,7 @@ hugo mod npm pack [flags] [args]
```
-b, --baseURL string hostname (and path) to the root, e.g. https://spf13.com/
--cacheDir string filesystem path to cache directory
--cacheDir string filesystem path to cache directory. Defaults: $TMPDIR/hugo_cache_$USER/
-c, --contentDir string filesystem path to content directory
-h, --help help for pack
-t, --theme strings themes to use (located in /themes/THEMENAME/)
+1 -1
View File
@@ -15,7 +15,7 @@ hugo mod tidy [flags] [args]
```
-b, --baseURL string hostname (and path) to the root, e.g. https://spf13.com/
--cacheDir string filesystem path to cache directory
--cacheDir string filesystem path to cache directory. Defaults: $TMPDIR/hugo_cache_$USER/
-c, --contentDir string filesystem path to content directory
-h, --help help for tidy
-t, --theme strings themes to use (located in /themes/THEMENAME/)
+1 -1
View File
@@ -21,7 +21,7 @@ hugo mod vendor [flags] [args]
```
-b, --baseURL string hostname (and path) to the root, e.g. https://spf13.com/
--cacheDir string filesystem path to cache directory
--cacheDir string filesystem path to cache directory. Defaults: $TMPDIR/hugo_cache_$USER/
-c, --contentDir string filesystem path to content directory
-h, --help help for vendor
-t, --theme strings themes to use (located in /themes/THEMENAME/)
+1 -1
View File
@@ -19,7 +19,7 @@ hugo mod verify [flags] [args]
```
-b, --baseURL string hostname (and path) to the root, e.g. https://spf13.com/
--cacheDir string filesystem path to cache directory
--cacheDir string filesystem path to cache directory. Defaults: $TMPDIR/hugo_cache_$USER/
--clean delete module cache for dependencies that fail verification
-c, --contentDir string filesystem path to content directory
-h, --help help for verify
+5 -1
View File
@@ -18,6 +18,10 @@ If archetypes are provided in your theme or site, they will be used.
Ensure you run this within the root directory of your site.
```
hugo new [command] [flags]
```
### Options
```
@@ -46,5 +50,5 @@ Ensure you run this within the root directory of your site.
* [hugo](/commands/hugo/) - hugo builds your site
* [hugo new content](/commands/hugo_new_content/) - Create new content for your site
* [hugo new site](/commands/hugo_new_site/) - Create a new site (skeleton)
* [hugo new theme](/commands/hugo_new_theme/) - Create a new theme (skeleton)
* [hugo new theme](/commands/hugo_new_theme/) - Create a new site (skeleton)
+8 -8
View File
@@ -10,13 +10,13 @@ Create new content for your site
### Synopsis
Create a new content file and automatically set the date and title.
It will guess which kind of file to create based on the path provided.
You can also specify the kind with `-k KIND`.
If archetypes are provided in your theme or site, they will be used.
Ensure you run this within the root directory of your site.
It will guess which kind of file to create based on the path provided.
You can also specify the kind with `-k KIND`.
If archetypes are provided in your theme or site, they will be used.
Ensure you run this within the root directory of your site.
```
hugo new content [path] [flags]
@@ -26,7 +26,7 @@ hugo new content [path] [flags]
```
-b, --baseURL string hostname (and path) to the root, e.g. https://spf13.com/
--cacheDir string filesystem path to cache directory
--cacheDir string filesystem path to cache directory. Defaults: $TMPDIR/hugo_cache_$USER/
-c, --contentDir string filesystem path to content directory
--editor string edit new content with this editor, if provided
-f, --force overwrite file if it already exists
+2 -3
View File
@@ -20,9 +20,8 @@ hugo new site [path] [flags]
### Options
```
-f, --force init inside non-empty directory
--format string preferred file format (toml, yaml or json) (default "toml")
-h, --help help for site
-f, --force init inside non-empty directory
-h, --help help for site
```
### Options inherited from parent commands
+5 -6
View File
@@ -5,17 +5,16 @@ url: /commands/hugo_new_theme/
---
## hugo new theme
Create a new theme (skeleton)
Create a new site (skeleton)
### Synopsis
Create a new theme (skeleton) called [name] in ./themes.
New theme is a skeleton. Please add content to the touched files. Add your
name to the copyright line in the license and adjust the theme.toml file
according to your needs.
Create a new site in the provided directory.
The new site will have the correct structure, but no content or theme yet.
Use `hugo new [contentPath]` to create new content.
```
hugo new theme [name] [flags]
hugo new theme [path] [flags]
```
### Options
+1 -1
View File
@@ -33,7 +33,7 @@ hugo server [command] [flags]
-D, --buildDrafts include content marked as draft
-E, --buildExpired include expired content
-F, --buildFuture include content with publishdate in the future
--cacheDir string filesystem path to cache directory
--cacheDir string filesystem path to cache directory. Defaults: $TMPDIR/hugo_cache_$USER/
--cleanDestinationDir remove files from destination not found in static directories
-c, --contentDir string filesystem path to content directory
--disableBrowserError do not show build errors in the browser
+2 -3
View File
@@ -1,10 +1,9 @@
---
title: Content management
linkTitle: Overview
title: Content Management
linkTitle: Content Management Overview
description: Hugo makes managing large static sites easy with support for archetypes, content types, menus, cross references, summaries, and more.
menu:
docs:
identifier: content-management-overview
parent: content-management
weight: 10
keywords: [source, organization]
@@ -13,7 +13,7 @@ weight: 140
aliases: [/content/archetypes/]
---
## What are archetypes?
## What are Archetypes?
**Archetypes** are content template files in the [archetypes directory] of your project that contain preconfigured [front matter] and possibly also a content disposition for your website's [content types]. These will be used when you run `hugo new`.
@@ -33,7 +33,7 @@ The above will create a new content file in `content/posts/my-first-post.md` usi
The last two list items are only applicable if you use a theme and it uses the `my-theme` theme name as an example.
## Create a new archetype template
## Create a New Archetype Template
A fictional example for the section `newsletter` and the archetype file `archetypes/newsletter.md`. Create a new file in `archetypes/newsletter.md` and open it in a text editor.
@@ -46,7 +46,7 @@ draft: true
**Insert Lead paragraph here.**
## New cool posts
## New Cool Posts
{{ range first 10 ( where .Site.RegularPages "Type" "cool" ) }}
* {{ .Title }}
@@ -1,8 +1,9 @@
---
title: Build options
title: Build Options
linkTitle: Build Options
description: Build options help define how Hugo must treat a given page when building the site.
keywords: [build,content,front matter, page resources]
categories: [fundamentals,content management]
categories: [content management]
menu:
docs:
parent: content-management
@@ -12,7 +13,7 @@ weight: 70
aliases: [/content/build-options/]
---
They are stored in a reserved front matter object named `_build` with the following defaults:
They are stored in a reserved Front Matter object named `_build` with the following defaults:
{{< code-toggle >}}
_build:
@@ -25,30 +26,38 @@ _build:
If `always`, the page will be treated as a published page, holding its dedicated output files (`index.html`, etc...) and permalink.
Valid values are:
We extended this property from a boolean to an enum in Hugo 0.76.0. Valid values are:
- `never`
: The page will not be included in any page collection.
- `always (default)`
: The page will be rendered to disk and get a `RelPermalink` etc.
- `link`
: The page will be not be rendered to disk, but will get a `RelPermalink`.
never
: The page will not be included in any page collection.
always (default)
: The page will be rendered to disk and get a `RelPermalink` etc.
link
: The page will be not be rendered to disk, but will get a `RelPermalink`.
#### list
Note that we extended this property from a boolean to an enum in Hugo 0.68.0.
Valid values are:
- `never`
: The page will not be included in any page collection.
- `always (default)`
: The page will be included in all page collections, e.g. `site.RegularPages`, `.Pages`.
- `local`
: The page will be included in any _local_ page collection, e.g. `.RegularPages`, `.Pages`. One use case for this would be to create fully navigable, but headless content sections.
never
: The page will not be included in any page collection.
always (default)
: The page will be included in all page collections, e.g. `site.RegularPages`, `$page.Pages`.
local
: The page will be included in any _local_ page collection, e.g. `$page.RegularPages`, `$page.Pages`. One use case for this would be to create fully navigable, but headless content sections.
If true, the page will be treated as part of the project's collections and, when appropriate, returned by Hugo's listing methods (`.Pages`, `.RegularPages` etc...).
#### publishResources
If set to `true` (default) the [Bundle's Resources](/content-management/page-bundles) will be published.
Setting this to `false` will still publish Resources on demand (when a resource's `.Permalink` or `.RelPermalink` is invoked from the templates) but will skip the others.
If set to true the [Bundle's Resources](/content-management/page-bundles) will be published.
Setting this to false will still publish Resources on demand (when a resource's `.Permalink` or `.RelPermalink` is invoked from the templates) but will skip the others.
{{% note %}}
Any page, regardless of their build options, will always be available using the [`.GetPage`](/functions/getpage) methods.
@@ -58,7 +67,7 @@ Any page, regardless of their build options, will always be available using the
#### Not publishing a page
Project needs a "Who We Are" content file for front matter and body to be used by the homepage but nowhere else.
Project needs a "Who We Are" content file for Front Matter and body to be used by the homepage but nowhere else.
{{< code-toggle file="content/who-we-are.md" fm=true copy=false >}}
title: Who we are
@@ -2,7 +2,7 @@
title: Comments
description: Hugo ships with an internal Disqus template, but this isn't the only commenting system that will work with your new Hugo website.
keywords: [sections,content,organization]
categories: [project organization]
categories: [project organization, fundamentals]
menu:
docs:
parent: content-management
@@ -34,9 +34,9 @@ For many websites, this is enough configuration. However, you also have the opti
* `disqus_title`
* `disqus_url`
### Render Hugo's built-in Disqus partial template
### Render Hugo's Built-in Disqus Partial Template
Disqus has its own [internal template](/templates/internal/#disqus) available, to render it add the following code where you want comments to appear:
Disqus has its own [internal template](https://gohugo.io/templates/internal/#disqus) available, to render it add the following code where you want comments to appear:
```go-html-template
{{ template "_internal/disqus.html" . }}
@@ -1,5 +1,6 @@
---
title: Links and cross references
title: Links and Cross References
linkTitle: Links and Cross References
description: Shortcodes for creating links to documents.
categories: [content management]
keywords: ["cross references","references", "anchors", "urls"]
@@ -18,7 +19,7 @@ The `ref` and `relref` shortcodes display the absolute and relative permalinks t
The `ref` and `relref` shortcodes require a single parameter: the path to a content document, with or without a file extension, with or without an anchor. Paths without a leading `/` are first resolved relative to the current page, then to the remainder of the site.
```text
```
.
└── content
├── about
@@ -77,7 +78,7 @@ To link to another language version of a document, use this syntax:
{{</* relref path="document.md" lang="ja" */>}}
```
### Get another output format
### Get another Output Format
To link to another Output Format of a document, use this syntax:
@@ -12,7 +12,7 @@ weight: 50
---
{{< new-in "0.93.0" >}}
## GoAT diagrams (Ascii)
## GoAT Diagrams (Ascii)
Hugo supports [GoAT](https://github.com/bep/goat) natively. This means that this code block:
@@ -42,14 +42,14 @@ Will be rendered as:
1 2 3 4 1 2 3 4 1 2 3 4 '--- 4 '-- 4 \ 4
```
## Mermaid diagrams
## Mermaid Diagrams
Hugo currently does not provide default templates for Mermaid diagrams. But you can easily add your own. One way to do it would be to create `layouts/_default/_markup/render-codeblock-mermaid.html`:
```go-html-template
<pre class="mermaid">
<div class="mermaid">
{{- .Inner | safeHTML }}
</pre>
</div>
{{ .Page.Store.Set "hasMermaid" true }}
```
@@ -66,7 +66,7 @@ And then include this snippet at the bottom of the content template (**Note**: b
With that you can use the `mermaid` language in Markdown code blocks:
````text
````
```mermaid
sequenceDiagram
participant Alice
@@ -82,7 +82,7 @@ sequenceDiagram
```
````
## Goat ASCII diagram examples
## Goat Ascii Diagram Examples
### Graphics
@@ -166,7 +166,7 @@ Created from <https://arthursonzogni.com/Diagon/#Tree>
```
### Sequence diagram
### Sequence Diagram
<https://arthursonzogni.com/Diagon/#Sequence>
+11 -4
View File
@@ -1,5 +1,6 @@
---
title: Content formats
title: Content Formats
linkTitle: Content Formats
description: Both HTML and Markdown are supported content formats.
categories: [content management]
keywords: [markdown,asciidoc,pandoc,content format]
@@ -33,7 +34,7 @@ The current list of content formats in Hugo:
The `markup identifier` is fetched from either the `markup` variable in front matter or from the file extension. For markup-related configuration, see [Configure Markup](/getting-started/configuration-markup/).
## External helpers
## External Helpers
Some of the formats in the table above need external helpers installed on your PC. For example, for AsciiDoc files,
Hugo will try to call the `asciidoctor` command. This means that you will have to install the associated
@@ -49,7 +50,13 @@ Hugo passes reasonable default arguments to these external helpers by default:
Because additional formats are external commands, generation performance will rely heavily on the performance of the external tool you are using. As this feature is still in its infancy, feedback is welcome.
{{% /note %}}
### External helper Asciidoctor
### External Helper AsciiDoc
[AsciiDoc](https://github.com/asciidoc/asciidoc) implementation EOLs in Jan 2020 and is no longer supported.
AsciiDoc development is being continued under [Asciidoctor](https://github.com/asciidoctor). The format AsciiDoc
remains of course. Please continue with the implementation Asciidoctor.
### External Helper Asciidoctor
The Asciidoctor community offers a wide set of tools for the AsciiDoc format that can be installed additionally to Hugo.
[See the Asciidoctor docs for installation instructions](https://asciidoctor.org/docs/install-toolchain/). Make sure that also all
@@ -106,7 +113,7 @@ parameters. Run Hugo with `-v`. You will get an output like
INFO 2019/12/22 09:08:48 Rendering book-as-pdf.adoc with C:\Ruby26-x64\bin\asciidoctor.bat using asciidoc args [--no-header-footer -r asciidoctor-html5s -b html5s -r asciidoctor-diagram --base-dir D:\prototypes\hugo_asciidoc_ddd\docs -a outdir=D:\prototypes\hugo_asciidoc_ddd\build -] ...
```
## Learn markdown
## Learn Markdown
Markdown syntax is simple enough to learn in a single sitting. The following are excellent resources to get you up and running:
@@ -1,5 +1,5 @@
---
title: Front matter
title: Front Matter
description: Hugo allows you to add front matter in yaml, toml, or json to your content files.
categories: [content management]
keywords: ["front matter", "yaml", "toml", "json", "metadata", "archetypes"]
@@ -16,7 +16,7 @@ aliases: [/content/front-matter/]
{{< youtube Yh2xKRJGff4 >}}
## Front matter formats
## Front Matter Formats
Hugo supports four formats for front matter, each with their own identifying tokens.
@@ -47,7 +47,7 @@ categories = [
slug = "spf13-vim-3-0-release-and-new-website"
{{< /code-toggle >}}
## Front matter variables
## Front Matter Variables
### Predefined
@@ -93,7 +93,7 @@ lastmod
: The datetime at which the content was last modified.
linkTitle
: Used for creating links to content; if set, Hugo defaults to using the `linkTitle` before the `title`. Hugo can also [order lists of content by `linkTitle`][bylinktitle].
: Used for creating links to content; if set, Hugo defaults to using the `linktitle` before the `title`. Hugo can also [order lists of content by `linktitle`][bylinktitle].
markup
: **experimental**; specify `"rst"` for reStructuredText (requires`rst2html`) or `"md"` (default) for Markdown.
@@ -135,10 +135,10 @@ weight
: Field name of the *plural* form of the index. See `tags` and `categories` in the above front matter examples. *Note that the plural form of user-defined taxonomies cannot be the same as any of the predefined front matter variables.*
{{% note %}}
If neither `slug` nor `url` is present and [permalinks are not configured otherwise in your site configuration file](/content-management/urls/#permalinks), Hugo will use the file name of your content to create the output URL. See [Content Organization](/content-management/organization) for an explanation of paths in Hugo and [URL Management](/content-management/urls/) for ways to customize Hugo's default behaviors.
If neither `slug` nor `url` is present and [permalinks are not configured otherwise in your site configuration file](/content-management/urls/#permalinks), Hugo will use the filename of your content to create the output URL. See [Content Organization](/content-management/organization) for an explanation of paths in Hugo and [URL Management](/content-management/urls/) for ways to customize Hugo's default behaviors.
{{% /note %}}
### User-defined
### User-Defined
You can add fields to your front matter arbitrarily to meet your needs. These user-defined key-values are placed into a single `.Params` variable for use in your templates.
@@ -149,11 +149,11 @@ include_toc: true
show_comments: false
{{</ code-toggle >}}
## Front matter cascade
## Front Matter Cascade
Any node or section can pass down to descendants a set of front matter values as long as defined underneath the reserved `cascade` front matter key.
Any node or section can pass down to descendants a set of Front Matter values as long as defined underneath the reserved `cascade` Front Matter key.
### Target specific pages
### Target Specific Pages
The `cascade` block can be a slice with a optional `_target` keyword, allowing for multiple `cascade` values targeting different page sets.
@@ -202,15 +202,15 @@ With the above example the Blog section page and its descendants will return `im
- Said descendant has its own `banner` value set
- Or a closer ancestor node has its own `cascade.banner` value set.
## Order content through front matter
## Order Content Through Front Matter
You can assign content-specific `weight` in the front matter of your content. These values are especially useful for [ordering][ordering] in list views. You can use `weight` for ordering of content and the convention of [`<TAXONOMY>_weight`][taxweight] for ordering content within a taxonomy. See [Ordering and Grouping Hugo Lists][lists] to see how `weight` can be used to organize your content in list views.
## Override global markdown configuration
## Override Global Markdown Configuration
It's possible to set some options for Markdown rendering in a content's front matter as an override to the [rendering options set in your project configuration][config].
It's possible to set some options for Markdown rendering in a content's front matter as an override to the [Rendering options set in your project configuration][config].
## Front matter format specs
## Front Matter Format Specs
- [TOML Spec][toml]
- [YAML Spec][yaml]
@@ -220,15 +220,15 @@ It's possible to set some options for Markdown rendering in a content's front ma
[aliases]: /content-management/urls/#aliases
[archetype]: /content-management/archetypes/
[bylinktitle]: /templates/lists/#by-link-title
[config]: /getting-started/configuration/
[config]: /getting-started/configuration/ "Hugo documentation for site configuration"
[content type]: /content-management/types/
[contentorg]: /content-management/organization/
[headless-bundle]: /content-management/page-bundles/#headless-bundle
[json]: https://www.ecma-international.org/publications/files/ECMA-ST/ECMA-404.pdf
[lists]: /templates/lists/#order-content
[lookup]: /templates/lookup-order/
[ordering]: /templates/lists/
[outputs]: /templates/output-formats/
[json]: https://www.ecma-international.org/publications/files/ECMA-ST/ECMA-404.pdf "Specification for JSON, JavaScript Object Notation"
[lists]: /templates/lists/#order-content "See how to order content in list pages; for example, templates that look to specific _index.md for content and front matter."
[lookup]: /templates/lookup-order/ "Hugo traverses your templates in a specific order when rendering content to allow for DRYer templating."
[ordering]: /templates/lists/ "Hugo provides multiple ways to sort and order your content in list templates"
[outputs]: /templates/output-formats/ "With the release of v22, you can output your content to any text format using Hugo's familiar templating"
[page-resources]: /content-management/page-resources/
[pagevars]: /variables/page/
[section]: /content-management/sections/
@@ -236,4 +236,4 @@ It's possible to set some options for Markdown rendering in a content's front ma
[toml]: https://toml.io/
[urls]: /content-management/urls/
[variables]: /variables/
[yaml]: https://yaml.org/spec/
[yaml]: https://yaml.org/spec/ "Specification for YAML, YAML Ain't Markup Language"
@@ -1,7 +1,7 @@
---
title: Image processing
title: Image Processing
description: Resize, crop, rotate, filter, and convert images.
categories: [fundamentals,content management]
categories: [content management]
keywords: [resources, images]
menu:
docs:
@@ -10,11 +10,11 @@ menu:
toc: true
weight: 90
---
## Image resources
## Image Resources
To process an image, you must access the image as either a page resource or a global resource.
### Page resources
### Page Resources
A page resource is a file within a [page bundle]. A page bundle is a directory with an `index.md` or `_index.md` file at its root.
@@ -26,7 +26,7 @@ content/
└── sunset.jpg <-- page resource
```
### Global resources
### Global Resources
A global resource is a file:
@@ -52,7 +52,7 @@ To access a remote image as a global resource:
{{ $image := resources.GetRemote "https://gohugo.io/img/hugo-logo.png" }}
```
## Image rendering
## Image Rendering
Once you have accessed an image as either a page resource or a global resource, render it in your templates using the `Permalink`, `RelPermalink`, `Width`, and `Height` properties.
@@ -80,12 +80,12 @@ Example 3: A more concise way to skip image rendering if the resource is not fou
{{ end }}
```
## Image processing methods
## Image Processing Methods
The `image` resource implements the [`Resize`], [`Fit`], [`Fill`], [`Crop`], [`Filter`], [`Colors`] and [`Exif`] methods.
{{% note %}}
Metadata (EXIF, IPTC, XMP, etc.) is not preserved during image transformation. Use the [`Exif`] method with the _original_ image to extract EXIF metadata from JPEG or TIFF images.
Metadata (Exif, IPTC, XMP, etc.) is not preserved during image transformation. Use the [`Exif`] method with the _original_ image to extract Exif metadata from JPEG or TIFF images.
{{% /note %}}
### Resize
@@ -164,11 +164,11 @@ Sometimes it can be useful to create the filter chain once and then reuse it.
This method is fast, but if you also scale down your images, it would be good for performance to extract the colors from the scaled down image.
### EXIF
### Exif
Provides an [EXIF] object containing image metadata.
Provides an [Exif] object containing image metadata.
You may access EXIF data in JPEG and TIFF images. To prevent errors when processing images without EXIF data, wrap the access in a [`with`] statement.
You may access Exif data in JPEG and TIFF images. To prevent errors when processing images without Exif data, wrap the access in a [`with`] statement.
```go-html-template
{{ with $image.Exif }}
@@ -181,7 +181,7 @@ You may access EXIF data in JPEG and TIFF images. To prevent errors when process
{{ end }}
```
You may also access EXIF fields individually, using the [`lang.FormatNumber`] function to format the fields as needed.
You may also access Exif fields individually, using the [`lang.FormatNumber`] function to format the fields as needed.
```go-html-template
{{ with $image.Exif }}
@@ -198,7 +198,7 @@ You may also access EXIF fields individually, using the [`lang.FormatNumber`] fu
{{ end }}
```
#### EXIF variables
#### Exif Variables
.Date
: Image creation date/time. Format with the [time.Format] function.
@@ -210,9 +210,9 @@ You may also access EXIF fields individually, using the [`lang.FormatNumber`] fu
: GPS longitude in degrees.
.Tags
: A collection of the available EXIF tags for this image. You may include or exclude specific tags from this collection in the [site configuration](#exif-data).
: A collection of the available Exif tags for this image. You may include or exclude specific tags from this collection in the [site configuration](#exif-data).
## Image processing options
## Image Processing Options
The [`Resize`], [`Fit`], [`Fill`], and [`Crop`] methods accept a space-separated, case-insensitive list of options. The order of the options within the list is irrelevant.
@@ -265,7 +265,7 @@ For example, if you have a 400x200 image with a bird in the upper left quadrant,
If you apply [rotation](#rotation) when using the [`Crop`] or [`Fill`] method, specify the anchor relative to the rotated image.
### Target format
### Target Format
By default, Hugo encodes the image in the source format. You may convert the image to another format by specifying `bmp`, `gif`, `jpeg`, `jpg`, `png`, `tif`, `tiff`, or `webp`.
@@ -313,7 +313,7 @@ The default value is `photo`. You may override the default value in the [site co
{{ $image.Resize "600x webp picture" }}
```
### Background color
### Background Color
When converting an image from a format that supports transparency (e.g., PNG) to a format that does _not_ support transparency (e.g., JPEG), you may specify the background color of the resulting image.
@@ -325,7 +325,7 @@ The default value is `#ffffff` (white). You may override the default value in th
{{ $image.Resize "600x jpg #b31280" }}
```
### Resampling filter
### Resampling Filter
You may specify the resampling filter used when resizing an image. Commonly used resampling filters include:
@@ -346,7 +346,7 @@ The default value is `Box`. You may override the default value in the [site conf
See [github.com/disintegration/imaging] for the complete list of resampling filters. If you wish to improve image quality at the expense of performance, you may wish to experiment with the alternative filters.
## Image processing examples
## Image Processing Examples
_The photo of the sunset used in the examples below is Copyright [Bjørn Erik Pedersen](https://commons.wikimedia.org/wiki/User:Bep) (Creative Commons Attribution-Share Alike 4.0 International license)_
@@ -378,9 +378,9 @@ Call the shortcode from your Markdown like this:
Note the self-closing shortcode syntax above. You may call the `imgproc` shortcode with or without **inner content**.
{{% /note %}}
## Imaging configuration
## Imaging Configuration
### Processing options
### Processing Options
Define an `imaging` section in your site configuration to set the default [image processing options](#image-processing-options).
@@ -408,9 +408,9 @@ quality
resampleFilter
: See image processing options: [resampling filter](#resampling-filter).
### EXIF data
### Exif Data
Define an `imaging.exif` section in your site configuration to control the availability of EXIF data.
Define an `imaging.exif` section in your site configuration to control the availability of Exif data.
{{< code-toggle file="hugo" copy=true >}}
[imaging.exif]
@@ -427,16 +427,16 @@ disableLatLong
: Hugo extracts the GPS latitude and longitude into `.Lat` and `.Long`. Set this to `true` to disable. Default is `false`.
excludeFields
: Regular expression matching the EXIF tags to exclude from the `.Tags` collection. Default is&nbsp;`""`.
: Regular expression matching the Exif tags to exclude from the `.Tags` collection. Default is&nbsp;`""`.
includeFields
: Regular expression matching the EXIF tags to include in the `.Tags` collection. Default is&nbsp;`""`. To include all available tags, set this value to&nbsp;`".*"`.
: Regular expression matching the Exif tags to include in the `.Tags` collection. Default is&nbsp;`""`. To include all available tags, set this value to&nbsp;`".*"`.
{{% note %}}
To improve performance and decrease cache size, if you set neither `excludeFields` nor `includeFields`, Hugo excludes the following tags: `ColorSpace`, `Contrast`, `Exif`, `Exposure[M|P|B]`, `Flash`, `GPS`, `JPEG`, `Metering`, `Resolution`, `Saturation`, `Sensing`, `Sharp`, and `WhiteBalance`.
{{% /note %}}
## Smart cropping of images
## Smart Cropping of Images
By default, Hugo uses the [Smartcrop] library when cropping images with the `Crop` or`Fill` methods. You can set the anchor point manually, but in most cases the `Smart` option will make a good choice.
@@ -446,7 +446,7 @@ Examples using the sunset image from above:
{{< imgproc sunset Crop "200x200 smart" />}}
## Image processing performance consideration
## Image Processing Performance Consideration
Hugo caches processed images in the `resources` directory. If you include this directory in source control, Hugo will not have to regenerate the images in a CI/CD workflow (e.g., GitHub Pages, GitLab Pages, Netlify, etc.). This results in faster builds.
@@ -458,7 +458,7 @@ hugo --gc
[time.Format]: /functions/dateformat
[`anchor`]: /content-management/image-processing#anchor
[mounted]: /hugo-modules/configuration#module-configuration-mounts
[mounted]: /hugo-modules/configuration#module-config-mounts
[page bundle]: /content-management/page-bundles
[`lang.FormatNumber`]: /functions/lang
[filters]: /functions/images
@@ -1,5 +1,5 @@
---
title: Multilingual mode
title: Multilingual Mode
linkTitle: Multilingual
description: Hugo supports the creation of websites with multiple languages side by side.
categories: [content management]
@@ -17,79 +17,57 @@ You should define the available languages in a `languages` section in your site
Also See [Hugo Multilingual Part 1: Content translation].
## Configure languages
## Configure Languages
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.
The following is an example of a site configuration for a multilingual Hugo project:
{{< code-toggle file="hugo" >}}
defaultContentLanguage = 'de'
defaultContentLanguageInSubdir = true
defaultContentLanguage = "en"
copyright = "Everything is mine"
[languages.de]
contentDir = 'content/de'
disabled = false
languageCode = 'de-DE'
languageDirection = 'ltr'
languageName = 'Deutsch'
title = 'Projekt Dokumentation'
weight = 1
[languages.de.params]
subtitle = 'Referenz, Tutorials und Erklärungen'
[params]
[params.navigation]
help = "Help"
[languages]
[languages.en]
contentDir = 'content/en'
disabled = false
languageCode = 'en-US'
languageDirection = 'ltr'
languageName = 'English'
title = 'Project Documentation'
weight = 2
title = "My blog"
weight = 1
[languages.en.params]
subtitle = 'Reference, Tutorials, and Explanations'
linkedin = "https://linkedin.com/whoever"
[languages.fr]
title = "Mon blogue"
weight = 2
[languages.fr.params]
linkedin = "https://linkedin.com/fr/whoever"
[languages.fr.params.navigation]
help = "Aide"
[languages.ar]
title = "مدونتي"
weight = 2
languagedirection = "rtl"
[languages.pt-pt]
title = "O meu blog"
weight = 3
{{< /code-toggle >}}
`defaultContentLanguage`
: (`string`) The project's default language tag as defined by [RFC 5646]. Must be lower case, and must match one of the defined language keys. Default is `en`. Examples:
Anything not defined in a `languages` block will fall back to the global value for that key (e.g., `copyright` for the English `en` language). This also works for `params`, as demonstrated with `help` above: You will get the value `Aide` in French and `Help` in all the languages without this parameter set.
- `en`
- `en-gb`
- `pt-br`
With the configuration above, all content, sitemap, RSS feeds, pagination,
and taxonomy pages will be rendered below `/` in English (your default content language) and then below `/fr` in French.
`defaultContentLanguageInSubdir`
: (`bool`) If `true`, Hugo renders the default language site in a subdirectory matching the `defaultContentLanguage`. Default is `false`.
When working with front matter `Params` in [single page templates], omit the `params` in the key for the translation.
`contentDir`
: (`string`) The content directory for this language. Omit if [translating by file name].
`defaultContentLanguage` sets the project's default language. If not set, the default language will be `en`.
`disabled`
: (`bool`) If `true`, Hugo will not render content for this language. Default is `false`.
If the default language needs to be rendered below its own language code (`/en`) like the others, set `defaultContentLanguageInSubdir: true`.
`languageCode`
: (`string`) The language tag as defined by [RFC 5646]. This value may include upper and lower case characters, hyphens or underscores, and does not affect localization or URLs. Hugo uses this value to populate the `language` element in the [built-in RSS template], and the `lang` attribute of the `html` element in the [built-in alias template]. Examples:
Only the obvious non-global options can be overridden per language. Examples of global options are `baseURL`, `buildDrafts`, etc.
- `en`
- `en-GB`
- `pt-BR`
`languageDirection`
: (`string`) The language direction, either left-to-right (`ltr`) or right-to-left (`rtl`). Use this value in your templates with the global [`dir`] HTML attribute.
`languageName`
: (`string`) The language name, typically used when rendering a language switcher.
`title`
: (`string`) The language title. When set, this overrides the site title for this language.
`weight`
: (`int`) The language weight. When set to a non-zero value, this is the primary sort criteria for this language.
[`dir`]: https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/dir
[built-in RSS template]: https://github.com/gohugoio/hugo/blob/master/tpl/tplimpl/embedded/templates/_default/rss.xml
[built-in alias template]: https://github.com/gohugoio/hugo/blob/master/tpl/tplimpl/embedded/templates/alias.html
[RFC 5646]: https://datatracker.ietf.org/doc/html/rfc5646
[translating by file name]: #translation-by-file-name
**Please note:** use lowercase language codes, even when using regional languages (ie. use pt-pt instead of pt-PT). Currently Hugo language internals lowercase language codes, which can cause conflicts with settings like `defaultContentLanguage` which are not lowercased. Please track the evolution of this issue in [Hugo repository issue tracker](https://github.com/gohugoio/hugo/issues/7344)
### Changes in Hugo 0.112.0
@@ -98,7 +76,7 @@ subtitle = 'Reference, Tutorials, and Explanations'
In Hugo `v0.112.0` we consolidated all configuration options, and improved how the languages and their parameters are merged with the main configuration. But while testing this on Hugo sites out there, we received some error reports and reverted some of the changes in favor of deprecation warnings:
1. `site.Language.Params` is deprecated. Use `site.Params` directly.
1. Adding custom parameters to the top level language configuration is deprecated, add all of these below `[params]`, see `color` in the example below.
1. Adding custom params to the top level language config is deprecated, add all of these below `[params]`, see `color` in the example below.
```toml
title = "My blog"
@@ -114,36 +92,35 @@ color = "blue"
In the example above, all settings except `color` below `params` map to predefined configuration options in Hugo for the site and its language, and should be accessed via the documented accessors:
```go-html-template
```
{{ site.Title }}
{{ site.LanguageCode }}
{{ site.Params.color }}
```
### Disable a language
### Disable a Language
To disable a language within a `languages` object in your site configuration:
You can disable one or more languages. This can be useful when working on a new translation.
{{< code-toggle file="hugo" copy=false >}}
[languages.es]
disabled = true
{{< code-toggle file="hugo" >}}
disableLanguages = ["fr", "ja"]
{{< /code-toggle >}}
To disable one or more languages in the root of your site configuration:
{{< code-toggle file="hugo" copy=false >}}
disableLanguages = ["es", "fr"]
{{< /code-toggle >}}
To disable one or more languages using an environment variable:
```bash
HUGO_DISABLELANGUAGES="es fr" hugo
```
Note that you cannot disable the default content language.
### Configure multilingual multihost
We kept this as a standalone setting to make it easier to set via [OS environment]:
```bash
HUGO_DISABLELANGUAGES="fr ja" hugo
```
If you have already a list of disabled languages in `hugo.toml`, you can enable them in development like this:
```bash
HUGO_DISABLELANGUAGES=" " hugo server
```
### Configure Multilingual Multihost
From **Hugo 0.31** we support multiple languages in a multihost configuration. See [this issue](https://github.com/gohugoio/hugo/issues/4027) for details.
@@ -190,11 +167,12 @@ Press Ctrl+C to stop
Live reload and `--navigateToChanged` between the servers work as expected.
## Translate your content
## Translate Your Content
There are two ways to manage your content translations. Both ensure each page is assigned a language and is linked to its counterpart translations.
### Translation by file name
### Translation by filename
Considering the following example:
@@ -204,9 +182,9 @@ Considering the following example:
The first file is assigned the English language and is linked to the second.
The second file is assigned the French language and is linked to the first.
Their language is __assigned__ according to the language code added as a __suffix to the file name__.
Their language is __assigned__ according to the language code added as a __suffix to the filename__.
By having the same **path and base file name**, the content pieces are __linked__ together as translated pages.
By having the same **path and base filename**, the content pieces are __linked__ together as translated pages.
{{% note %}}
If a file has no language code, it will be assigned the default language.
@@ -214,7 +192,7 @@ If a file has no language code, it will be assigned the default language.
### Translation by content directory
This system uses different content directories for each of the languages. Each language's content directory is set using the `contentDir` parameter.
This system uses different content directories for each of the languages. Each language's content directory is set using the `contentDir` param.
{{< code-toggle file="hugo" >}}
languages:
@@ -256,11 +234,11 @@ Considering the following example:
translationKey: "about"
{{< /code-toggle >}}
By setting the `translationKey` front matter parameter to `about` in all three pages, they will be __linked__ as translated pages.
By setting the `translationKey` front matter param to `about` in all three pages, they will be __linked__ as translated pages.
### Localizing permalinks
Because paths and file names are used to handle linking, all translated pages will share the same URL (apart from the language subdirectory).
Because paths and filenames are used to handle linking, all translated pages will share the same URL (apart from the language subdirectory).
To localize URLs:
@@ -279,7 +257,7 @@ slug: "a-propos"
At render, Hugo will build both `/about/` and `/fr/a-propos/` without affecting the translation link.
### Page bundles
### Page Bundles
To avoid the burden of having to duplicate files, each Page Bundle inherits the resources of its linked translated pages' bundles except for the content files (Markdown files, HTML files etc...).
@@ -291,10 +269,10 @@ If, across the linked bundles, two or more files share the same basename, only o
* First file found across bundles by order of language `Weight`.
{{% note %}}
Page Bundle resources follow the same language assignment logic as content files, both by file name (`image.jpg`, `image.fr.jpg`) and by directory (`english/about/header.jpg`, `french/about/header.jpg`).
Page Bundle resources follow the same language assignment logic as content files, both by filename (`image.jpg`, `image.fr.jpg`) and by directory (`english/about/header.jpg`, `french/about/header.jpg`).
{{%/ note %}}
## Reference translated content
## Reference the Translated Content
To create a list of links to translated content, use a template similar to the following:
@@ -315,7 +293,7 @@ The above can be put in a `partial` (i.e., inside `layouts/partials/`) and inclu
The above also uses the [`i18n` function][i18func] described in the next section.
### List all available languages
### List All Available Languages
`.AllTranslations` on a `Page` can be used to list all translations, including the page itself. On the home page it can be used to build a language navigator:
@@ -327,7 +305,7 @@ The above also uses the [`i18n` function][i18func] described in the next section
</ul>
{{< /code >}}
## Translation of strings
## Translation of Strings
Hugo uses [go-i18n] to support string translations. [See the project's source repository][go-i18n-source] to find tools that will help you manage your translation workflows.
@@ -607,7 +585,7 @@ weight = 20
For a simple menu with two languages, these menu entries are easy to create and maintain. For a larger menu, or with more than two languages, using translation tables as described above is preferable.
## Missing translations
## Missing Translations
If a string does not have a translation for the current language, Hugo will use the value from the default language. If no default value is set, an empty string will be shown.
@@ -626,7 +604,7 @@ hugo --printI18nWarnings | grep i18n
i18n|MISSING_TRANSLATION|en|wordCount
```
## Multilingual themes support
## Multilingual Themes support
To support Multilingual mode in your themes, some considerations must be taken for the URLs in the templates. If there is more than one language, URLs must meet the following criteria:
@@ -1,8 +1,8 @@
---
title: Content organization
title: Content Organization
linkTitle: Organization
description: Hugo assumes that the same structure that works to organize your source content is used to organize the rendered site.
categories: [fundamentals,content management]
categories: [content management,fundamentals]
keywords: [sections,content,organization,bundle,resources]
menu:
docs:
@@ -13,7 +13,7 @@ weight: 20
aliases: [/content/sections/]
---
## Page bundles
## Page Bundles
Hugo `0.32` announced page-relative images and other resources packaged into `Page Bundles`.
@@ -29,7 +29,7 @@ The bundle documentation is a **work in progress**. We will publish more compreh
{{% /note %}}
## Organization of content source
## Organization of Content Source
In Hugo, your content should be organized in a manner that reflects the rendered website.
@@ -52,12 +52,12 @@ Without any additional configuration, the following will automatically work:
└── second.md // <- https://example.com/quote/second/
```
## Path breakdown in Hugo
## Path Breakdown in Hugo
The following demonstrates the relationships between your content organization and the output URL structure for your Hugo website when it renders. These examples assume you are [using pretty URLs][pretty], which is the default behavior for Hugo. The examples also assume a key-value of `baseURL = "https://example.com"` in your [site's configuration file][config].
### Index pages: `_index.md`
### Index Pages: `_index.md`
`_index.md` has a special role in Hugo. It allows you to add front matter and content to your [list templates][lists]. These templates include those for [section templates], [taxonomy templates], [taxonomy terms templates], and your [homepage template].
@@ -94,7 +94,7 @@ https://example.com/posts/index.html
The [sections] can be nested as deeply as you want. The important thing to understand is that to make the section tree fully navigational, at least the lower-most section must include a content file. (i.e. `_index.md`).
### Single pages in sections
### Single Pages in Sections
Single content files in each of your sections will be rendered as [single page templates][singles]. Here is an example of a single `post` within `posts`:
@@ -121,7 +121,7 @@ https://example.com/posts/my-first-hugo-post/index.html
```
## Paths explained
## Paths Explained
The following concepts provide more insight into the relationship between your project's organization and the default Hugo behavior when building output for the website.
@@ -1,5 +1,5 @@
---
title: Page bundles
title: Page Bundles
description: Content organization using Page Bundles
keywords: [page, bundle, leaf, branch]
categories: [content management]
@@ -19,22 +19,23 @@ A Page Bundle can be one of:
- Branch Bundle (home page, section, taxonomy terms, taxonomy list)
| | Leaf Bundle | Branch Bundle |
|-------------------------------------|----------------------------------------------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
|-------------------------------------|----------------------------------------------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Usage | Collection of content and attachments for single pages | Collection of attachments for section pages (home page, section, taxonomy terms, taxonomy list) |
| Index file name | `index.md` [^fn:1] | `_index.md` [^fn:1] |
| Index filename | `index.md` [^fn:1] | `_index.md` [^fn:1] |
| Allowed Resources | Page and non-page (like images, PDF, etc.) types | Only non-page (like images, PDF, etc.) types |
| Where can the Resources live? | At any directory level within the leaf bundle directory. | Only in the directory level **of** the branch bundle directory i.e. the directory containing the `_index.md` ([ref](https://discourse.gohugo.io/t/question-about-content-folder-structure/11822/4?u=kaushalmodi)). |
| Layout type | [`single`](/templates/single-page-templates/) | [`list`](/templates/lists) |
| Layout type | `single` | `list` |
| Nesting | Does not allow nesting of more bundles under it | Allows nesting of leaf or branch bundles under it |
| Example | `content/posts/my-post/index.md` | `content/posts/_index.md` |
| Content from non-index page files...| Accessed only as page resources | Accessed only as regular pages |
| Content from non-index page files... | Accessed only as page resources | Accessed only as regular pages |
## Leaf bundles
## Leaf Bundles {#leaf-bundles}
A _Leaf Bundle_ is a directory at any hierarchy within the `content/`
directory, that contains an **`index.md`** file.
### Examples of leaf bundle organization {#examples-of-leaf-bundle-organization}
### Examples of Leaf Bundle organization {#examples-of-leaf-bundle-organization}
```text
content/
@@ -91,7 +92,7 @@ as long as it is not inside another **leaf** bundle.
{{% /note %}}
### Headless bundle
### Headless Bundle {#headless-bundle}
A headless bundle is a bundle that is configured to not get published
anywhere:
@@ -125,7 +126,7 @@ Explanation of the above example:
---
A leaf bundle can be made headless by adding below in the front matter
A leaf bundle can be made headless by adding below in the Front Matter
(in the `index.md`):
{{< code-toggle file="content/headless/index.md" fm=true copy=false >}}
@@ -137,7 +138,7 @@ There are many use cases of such headless page bundles:
- Shared media galleries
- Reusable page content "snippets"
## Branch bundles
## Branch Bundles {#branch-bundles}
A _Branch Bundle_ is any directory at any hierarchy within the
`content/` directory, that contains at least an **`_index.md`** file.
@@ -150,7 +151,7 @@ type as a content resource as long as it is a content type recognized by Hugo.
{{% /note %}}
### Examples of branch bundle organization
### Examples of Branch Bundle organization {#examples-of-branch-bundle-organization}
```text
content/
@@ -1,5 +1,5 @@
---
title: Page resources
title: Page Resources
description: Page resources -- images, other pages, documents, etc. -- have page-relative URLs and their own metadata.
categories: [content management]
keywords: [bundle,content,resources]
@@ -42,7 +42,7 @@ 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`.
Name
: Default value is the file name (relative to the owning page). Can be set in front matter.
: Default value is the filename (relative to the owning page). Can be set in front matter.
Title
: Default value is the same as `.Name`. Can be set in front matter.
@@ -67,21 +67,21 @@ with the contents of the file. Use this to create inline resources.
{{ end }}
{{ with .Resources.GetMatch "img.png" }}
<img src="data:{{ .MediaType.Type }};base64,{{ .Content | base64Encode }}">
<img src="data:{{ .MediaType }};base64,{{ .Content | base64Encode }}">
{{ end }}
```
MediaType.Type
: The media type (formerly known as a MIME type) of the resource (e.g., `image/jpeg`).
MediaType
: The MIME type of the resource, such as `image/jpeg`.
MediaType.MainType
: The main type of the resource's media type (e.g., `image`).
: The main type of the resource's MIME type. For example, a file of MIME type `application/pdf` has for MainType `application`.
MediaType.SubType
: The subtype of the resource's type (e.g., `jpeg`). This may or may not correspond to the file suffix.
: The subtype of the resource's MIME type. For example, a file of MIME type `application/pdf` has for SubType `pdf`. Note that this is not the same as the file extension. For example, Microsoft PowerPoint files (`.ppt`) have a subtype of `vnd.ms-powerpoint`.
MediaType.Suffixes
: A slice of possible file suffixes for the resource's media type (e.g., `[jpg jpeg jpe jif jfif]`).
: A slice of possible suffixes for the resource's MIME type.
## Methods
@@ -101,7 +101,7 @@ Match
GetMatch
: Same as `Match` but will return the first match.
### Pattern matching
### Pattern Matching
```go
// Using Match/GetMatch to find this images/sunset.jpg ?
@@ -115,7 +115,7 @@ GetMatch
```
## Page resources metadata
## Page Resources Metadata
The page resources' metadata is managed from the corresponding page's front matter with an array/table parameter named `resources`. You can batch assign values using [wildcards](https://tldp.org/LDP/GNU-Linux-Tools-Summary/html/x11655.htm).
+10 -10
View File
@@ -1,5 +1,5 @@
---
title: Related content
title: Related Content
description: List related content in "See Also" sections.
categories: [content management]
keywords: [content]
@@ -12,9 +12,9 @@ weight: 110
aliases: [/content/related/,/related/]
---
Hugo uses a set of factors to identify a page's related content based on front matter parameters. This can be tuned to the desired set of indices and parameters or left to Hugo's default [Related Content configuration](#configure-related-content).
Hugo uses a set of factors to identify a page's related content based on Front Matter parameters. This can be tuned to the desired set of indices and parameters or left to Hugo's default [Related Content configuration](#configure-related-content).
## List related content
## List Related Content
To list up to 5 related pages (which share the same _date_ or _keyword_ parameters) is as simple as including something similar to this partial in your single page template:
@@ -60,7 +60,7 @@ A fictional example using all of the above options:
We improved and simplified this feature in Hugo 0.111.0. Before this we had 3 different methods: `Related`, `RelatedTo` and `RelatedIndicies`. Now we have only one method: `Related`. The old methods are still available but deprecated. Also see [this blog article](https://regisphilibert.com/blog/2018/04/hugo-optmized-relashionships-with-related-content/) for a great explanation of more advanced usage of this feature.
{{% /note %}}
## Index content headings in related content
## Index Content Headings in Related Content
{{< new-in "0.111.0" >}}
@@ -105,7 +105,7 @@ weight = 80
{{ end }}
```
## Configure related content
## Configure Related Content
Hugo provides a sensible default configuration of Related Content, but you can fine-tune this in your configuration, on the global or language level if needed.
@@ -130,10 +130,10 @@ Note that if you have configured `tags` as a taxonomy, `tags` will also be added
Custom configuration should be set using the same syntax.
{{% note %}}
If you add a `related` configuration section, you need to add a complete configuration. It is not possible to just set, say, `includeNewer` and use the rest from the Hugo defaults.
If you add a `related` config section, you need to add a complete configuration. It is not possible to just set, say, `includeNewer` and use the rest from the Hugo defaults.
{{% /note %}}
### Top level configuration options
### Top Level Config Options
threshold
: A value between 0-100. Lower value will give more, but maybe not so relevant, matches.
@@ -144,10 +144,10 @@ includeNewer
toLower
: Set to true to lower case keywords in both the indexes and the queries. This may give more accurate results at a slight performance penalty. Note that this can also be set per index.
### Configuration options per index
### Config Options per Index
name
: The index name. This value maps directly to a page parameter. Hugo supports string values (`author` in the example) and lists (`tags`, `keywords` etc.) and time and date objects.
: The index name. This value maps directly to a page param. Hugo supports string values (`author` in the example) and lists (`tags`, `keywords` etc.) and time and date objects.
type
: {{< new-in "0.111.0" >}}. One of `basic`(default) or `fragments`.
@@ -168,7 +168,7 @@ pattern
toLower
: See above.
## Performance considerations
## Performance Considerations
**Fast is Hugo's middle name** and we would not have released this feature had it not been blistering fast.
@@ -1,5 +1,6 @@
---
title: Sections
title: Content Sections
linkTitle: Sections
description: Hugo generates a **section tree** that matches your content.
categories: [content management]
keywords: [lists,sections,content types,organization]
@@ -30,7 +31,7 @@ A **section** cannot be defined or overridden by a front matter parameter -- it
is strictly derived from the content organization structure.
{{% /note %}}
## Nested sections
## Nested Sections
The sections can be nested as deeply as you need.
@@ -54,7 +55,7 @@ currently always the *root section* only (`/blog/funny-cats/mypost/ => blog`).
If you need a specific template for a sub-section, you need to adjust either the `type` or `layout` in front matter.
{{% /note %}}
## Example: breadcrumb navigation
## Example: Breadcrumb Navigation
With the available [section variables and methods](#section-page-variables-and-methods) you can build powerful navigation. One common example would be a partial to show Breadcrumb navigation:
@@ -73,17 +74,17 @@ With the available [section variables and methods](#section-page-variables-and-m
</nav>
{{< /code >}}
## Section page variables and methods
## Section Page Variables and Methods
Also see [Page Variables](/variables/page/).
{{< readfile file="/content/en/readfiles/sectionvars.md" markdown="true" >}}
## Content section lists
## Content Section Lists
Hugo will automatically create a page for each *root section* that lists all the content in that section. See the documentation on [section templates] for details on customizing the way these pages are rendered.
## Content *section* vs. content *type*
## Content *Section* vs Content *Type*
By default, everything created within a section will use the [content `type`][content type] that matches the *root section* name. For example, Hugo will assume that `posts/post-1.md` has a `posts` content `type`. If you are using an [archetype] for your `posts` section, Hugo will generate front matter according to what it finds in `archetypes/posts.md`.
@@ -13,7 +13,7 @@ aliases: [/extras/shortcodes/]
testparam: "Hugo Rocks!"
---
## What a shortcode is
## What a Shortcode is
Hugo loves Markdown because of its simple content format, but there are times when Markdown falls short. Often, content authors are forced to add raw HTML (e.g., video `<iframe>`'s) to Markdown content. We think this contradicts the beautiful simplicity of Markdown's syntax.
@@ -23,7 +23,7 @@ A shortcode is a simple snippet inside a content file that Hugo will render usin
In addition to cleaner Markdown, shortcodes can be updated any time to reflect new classes, techniques, or standards. At the point of site generation, Hugo shortcodes will easily merge in your changes. You avoid a possibly complicated search and replace operation.
## Use shortcodes
## Use Shortcodes
{{< youtube 2xkNJL4gJ9E >}}
@@ -54,7 +54,7 @@ You can pass multiple lines as parameters to a shortcode by using raw string lit
and a new line with a "quoted string".` */>}}
```
### Shortcodes with markdown
### Shortcodes with Markdown
In Hugo `0.55` we changed how the `%` delimiter works. Shortcodes using the `%` as the outer-most delimiter will now be fully rendered when sent to the content renderer. They can be part of the generated table of contents, footnotes, etc.
@@ -64,7 +64,7 @@ If you want the old behavior, you can put the following line in the start of you
{{ $_hugo_config := `{ "version": 1 }` }}
```
### Shortcodes without markdown
### Shortcodes Without Markdown
The `<` character indicates that the shortcode's inner content does *not* need further rendering. Often shortcodes without Markdown include internal HTML:
@@ -72,11 +72,11 @@ The `<` character indicates that the shortcode's inner content does *not* need f
{{</* myshortcode */>}}<p>Hello <strong>World!</strong></p>{{</* /myshortcode */>}}
```
### Nested shortcodes
### Nested Shortcodes
You can call shortcodes within other shortcodes by creating your own templates that leverage the `.Parent` variable. `.Parent` allows you to check the context in which the shortcode is being called. See [Shortcode templates][sctemps].
## Use Hugo's built-in shortcodes
## Use Hugo's Built-in Shortcodes
Hugo ships with a set of predefined shortcodes that represent very common usage. These shortcodes are provided for author convenience and to keep your Markdown content clean.
@@ -125,13 +125,13 @@ attr
attrlink
: If the attribution text needs to be hyperlinked, URL of the destination.
#### Example `figure` input
#### Example `figure` Input
{{< code file="figure-input-example.md" >}}
{{</* figure src="elephant.jpg" title="An elephant at sunset" */>}}
{{</* figure src="elephant.jpg" title=">An elephant at sunset" */>}}
{{< /code >}}
#### Example `figure` output
#### Example `figure` Output
```html
<figure>
@@ -254,17 +254,17 @@ Include this in your markdown:
### `param`
Gets a value from the current `Page's` parameters set in front matter, with a fallback to the site parameter value. It will log an `ERROR` if the parameter with the given key could not be found in either.
Gets a value from the current `Page's` params set in front matter, with a fallback to the site param value. It will log an `ERROR` if the param with the given key could not be found in either.
```bash
{{</* param testparam */>}}
```
Since `testparam` is a parameter defined in front matter of this page with the value `Hugo Rocks!`, the above will print:
Since `testparam` is a param defined in front matter of this page with the value `Hugo Rocks!`, the above will print:
{{< param testparam >}}
To access deeply nested parameters, use "dot syntax", e.g:
To access deeply nested params, use "dot syntax", e.g:
```bash
{{</* param "my.nested.param" */>}}
@@ -282,14 +282,14 @@ Read a more extensive description of `ref` and `relref` in the [cross references
`ref` and `relref` take exactly one required parameter of _reference_, quoted and in position `0`.
#### Example `ref` and `relref` input
#### Example `ref` and `relref` Input
```go-html-template
[Neat]({{</* ref "blog/neat.md" */>}})
[Who]({{</* relref "about.md#who" */>}})
```
#### Example `ref` and `relref` output
#### Example `ref` and `relref` Output
Assuming that standard Hugo pretty URLs are turned on.
@@ -350,7 +350,7 @@ The `youtube` shortcode embeds a responsive video player for [YouTube videos]. O
https://www.youtube.com/watch?v=w7Ft2ymGmfc
```
#### Example `youtube` input
#### Example `youtube` Input
Copy the YouTube video ID that follows `v=` in the video's URL and pass it to the `youtube` shortcode:
@@ -371,7 +371,7 @@ For [accessibility reasons](https://dequeuniversity.com/tips/provide-iframe-titl
{{</* youtube id="w7Ft2ymGmfc" title="A New Hugo Site in Under Two Minutes" */>}}
{{< /code >}}
#### Example `youtube` output
#### Example `youtube` Output
Using the preceding `youtube` example, the following HTML will be added to your rendered website's markup:
@@ -379,17 +379,17 @@ Using the preceding `youtube` example, the following HTML will be added to your
{{< youtube id="w7Ft2ymGmfc" autoplay="true" >}}
{{< /code >}}
#### Example `youtube` display
#### Example `youtube` Display
Using the preceding `youtube` example (without `autoplay="true"`), the following simulates the displayed experience for visitors to your website. Naturally, the final display will be contingent on your style sheets and surrounding markup. The video is also include in the [Quick Start of the Hugo documentation][quickstart].
{{< youtube w7Ft2ymGmfc >}}
## Privacy configuration
## Privacy Config
To learn how to configure your Hugo site to meet the new EU privacy regulation, see [Hugo and the GDPR].
## Create custom shortcodes
## Create Custom Shortcodes
To learn more about creating custom shortcodes, see the [shortcode template documentation].
@@ -1,5 +1,6 @@
---
title: Static files
title: Static Files
linkTitle: Static Files
description: Files that get served **statically** (as-is, no modification) on the site root.
categories: [content management]
keywords: [source, directories]
@@ -17,7 +18,7 @@ all **static files** (e.g. stylesheets, JavaScript, images). The static files ar
Hugo can be configured to look into a different directory, or even
**multiple directories** for such static files by configuring the
`staticDir` parameter in the [site configuration]. All the files in all the
`staticDir` parameter in the [site config]. All the files in all the
static directories will form a union filesystem.
This union filesystem will be served from your site root. So a file
@@ -64,5 +65,5 @@ Note 2
: The example above is a [multihost setup]. In a regular setup, all
the static directories will be available to all sites.
[site configuration]: /getting-started/configuration/#all-configuration-settings
[site config]: /getting-started/configuration/#all-configuration-settings
[multihost setup]: /content-management/multilingual/#configure-multilingual-multihost
@@ -1,5 +1,5 @@
---
title: Content summaries
title: Content Summaries
linkTitle: Summaries
description: Hugo generates summaries of your content.
categories: [content management]
@@ -15,7 +15,7 @@ aliases: [/content/summaries/,/content-management/content-summaries/]
With the use of the `.Summary` [page variable][pagevariables], Hugo generates summaries of content to use as a short version in summary views.
## Summary splitting options
## Summary Splitting Options
* Automatic Summary Split
* Manual Summary Split
@@ -23,7 +23,7 @@ With the use of the `.Summary` [page variable][pagevariables], Hugo generates su
It is natural to accompany the summary with links to the original content, and a common design pattern is to see this link in the form of a "Read More ..." button. See the `.RelPermalink`, `.Permalink`, and `.Truncated` [page variables][pagevariables].
### Automatic summary splitting
### Automatic Summary Splitting
By default, Hugo automatically takes the first 70 words of your content as its summary and stores it into the `.Summary` page variable for use in your templates. You may customize the summary length by setting `summaryLength` in your [site configuration](/getting-started/configuration/).
@@ -35,7 +35,7 @@ You can customize how HTML tags in the summary are loaded using functions such a
The Hugo-defined summaries are set to use word count calculated by splitting the text by one or more consecutive whitespace characters. If you are creating content in a `CJK` language and want to use Hugo's automatic summary splitting, set `hasCJKLanguage` to `true` in your [site configuration](/getting-started/configuration/).
{{% /note %}}
### Manual summary splitting
### Manual Summary Splitting
Alternatively, you may add the <code>&#60;&#33;&#45;&#45;more&#45;&#45;&#62;</code> summary divider where you want to split the article.
@@ -57,7 +57,7 @@ Cons
Be careful to enter <code>&#60;&#33;&#45;&#45;more&#45;&#45;&#62;</code> exactly; i.e., all lowercase and with no whitespace.
{{% /note %}}
### Front matter summary
### Front Matter Summary
You might want your summary to be something other than the text that starts the article. In this case you can provide a separate summary in the `summary` variable of the article front matter.
@@ -67,7 +67,7 @@ Pros
Cons
: Extra work for content authors as they need to write an entirely separate piece of text as the summary of the article.
## Summary selection order
## Summary Selection Order
Because there are multiple ways in which a summary can be specified it is useful to understand the order of selection Hugo follows when deciding on the text to be returned by `.Summary`. It is as follows:
@@ -79,7 +79,7 @@ Because there are multiple ways in which a summary can be specified it is useful
Hugo uses the _first_ of the above steps that returns text. So if, for example, your article has both `summary` variable in its front matter and a <code>&#60;&#33;&#45;&#45;more&#45;&#45;&#62;</code> summary divider Hugo will use the manual summary split method.
{{% /note %}}
## Example: first 10 articles with summaries
## Example: First 10 Articles with Summaries
You can show content summaries with the following code. You could use the following snippet, for example, in a [section template].
@@ -1,5 +1,5 @@
---
title: Syntax highlighting
title: Syntax Highlighting
description: Hugo comes with really fast syntax highlighting from Chroma.
keywords: [highlighting,chroma,code blocks,syntax]
categories: [content management]
@@ -14,13 +14,13 @@ aliases: [/extras/highlighting/,/extras/highlight/,/tools/syntax-highlighting/]
Hugo uses [Chroma](https://github.com/alecthomas/chroma) as its code highlighter; it is built in Go and is really, really fast.
## Configure syntax highlighter
## Configure Syntax Highlighter
See [Configure Highlight](/getting-started/configuration-markup#highlight).
## Generate syntax highlighter CSS
## Generate Syntax Highlighter CSS
If you run with `markup.highlight.noClasses=false` in your site configuration, you need a style sheet.
If you run with `markup.highlight.noClasses=false` in your site config, you need a style sheet.
You can generate one with Hugo:
@@ -30,20 +30,20 @@ hugo gen chromastyles --style=monokai > syntax.css
Run `hugo gen chromastyles -h` for more options. See https://xyproto.github.io/splash/docs/ for a gallery of available styles.
## Highlight shortcode
## Highlight Shortcode
Highlighting is carried out via the built-in [`highlight` shortcode](/content-management/shortcodes/#highlight). It takes exactly one required parameter for the programming language to be highlighted and requires a closing shortcode.
Highlighting is carried out via the built-in [`highlight` shortcode](https://gohugo.io/content-management/shortcodes/#highlight). It takes exactly one required parameter for the programming language to be highlighted and requires a closing shortcode.
Options:
* `linenos`: configure line numbers. Valid values are `true`, `false`, `table`, or `inline`. `false` will turn off line numbers if it's configured to be on in site configuration. `table` will give copy-and-paste friendly code blocks.
* `linenos`: configure line numbers. Valid values are `true`, `false`, `table`, or `inline`. `false` will turn off line numbers if it's configured to be on in site config. `table` will give copy-and-paste friendly code blocks.
* `hl_lines`: lists a set of line numbers or line number ranges to be highlighted.
* `linenostart=199`: starts the line number count from 199.
* `anchorlinenos`: Configure anchors on line numbers. Valid values are `true` or `false`;
* `lineanchors`: Configure a prefix for the anchors on line numbers. Will be suffixed with `-`, so linking to the line number 1 with the option `lineanchors=prefix` adds the anchor `prefix-1` to the page.
* `hl_inline` Highlight inside a `<code>` (inline HTML element) tag. Valid values are `true` or `false`. The `code` tag will get a class with name `code-inline`. {{< new-in "0.101.0" >}}
### Example: highlight shortcode
### Example: Highlight Shortcode
```go-html-template
{{</* highlight go "linenos=table,hl_lines=8 15-17,linenostart=199" */>}}
@@ -76,9 +76,9 @@ func GetTitleFunc(style string) func(s string) string {
}
{{< / highlight >}}
## Highlight Hugo/Go template code
## Highlight Hugo/GO Template Code
For highlighting Hugo/Go template code on your page, add `/*` after the opening double curly braces and `*/` before closing curly braces.
For highlighting Hugo/GO template code on your page, add `/*` after the opening double curly braces and `*/` before closing curly braces.
``` go
{{</*/* myshortcode */*/>}}
@@ -90,11 +90,11 @@ Gives this:
{{</* myshortcode */>}}
```
## Highlight template function
## Highlight Template Func
See [Highlight](/functions/highlight/).
## Highlighting in code fences
## Highlighting in Code Fences
Highlighting in code fences is enabled by default.
@@ -132,7 +132,7 @@ func GetTitleFunc(style string) func(s string) string {
The options are the same as in the [highlighting shortcode](/content-management/syntax-highlighting/#highlight-shortcode), including `linenos=false`, but note the slightly different Markdown attribute syntax.
## List of Chroma highlighting languages
## List of Chroma Highlighting Languages
The full list of Chroma lexers and their aliases (which is the identifier used in the `highlight` template func or when doing highlighting in code fences):
@@ -12,7 +12,7 @@ weight: 150
aliases: [/taxonomies/overview/,/taxonomies/usage/,/indexes/overview/,/doc/indexes/,/extras/indexes]
---
## What is a taxonomy?
## What is a Taxonomy?
Hugo includes support for user-defined groupings of content called **taxonomies**. Taxonomies are classifications of logical relationships between content.
@@ -28,7 +28,7 @@ Value
: a piece of content assigned to a term
## Example taxonomy: movie website
## Example Taxonomy: Movie Website
Let's assume you are making a website about movies. You may want to include the following taxonomies:
@@ -41,7 +41,7 @@ Let's assume you are making a website about movies. You may want to include the
Then, in each of the movies, you would specify terms for each of these taxonomies (i.e., in the [front matter] of each of your movie content files). From these terms, Hugo would automatically create pages for each Actor, Director, Studio, Genre, Year, and Award, with each listing all of the Movies that matched that specific Actor, Director, Studio, Genre, Year, and Award.
### Movie taxonomy organization
### Movie Taxonomy Organization
To continue with the example of a movie site, the following demonstrates content relationships from the perspective of the taxonomy:
@@ -76,11 +76,11 @@ Moonrise Kingdom <- Value
...
```
## Default taxonomies
## Hugo Taxonomy Defaults {#default-taxonomies}
Hugo natively supports taxonomies.
Without adding a single line to your [site configuration] file, Hugo will automatically create taxonomies for `tags` and `categories`. That would be the same as manually [configuring your taxonomies](#configure-taxonomies) as below:
Without adding a single line to your [site config][config] file, Hugo will automatically create taxonomies for `tags` and `categories`. That would be the same as manually [configuring your taxonomies](#configure-taxonomies) as below:
{{< code-toggle file="hugo" copy=false >}}
[taxonomies]
@@ -88,7 +88,7 @@ Without adding a single line to your [site configuration] file, Hugo will automa
category = "categories"
{{</ code-toggle >}}
If you do not want Hugo to create any taxonomies, set `disableKinds` in your [site configuration] to the following:
If you do not want Hugo to create any taxonomies, set `disableKinds` in your [site config][config] to the following:
{{< code-toggle file="hugo" copy=false >}}
disableKinds = ["taxonomy","term"]
@@ -96,18 +96,18 @@ disableKinds = ["taxonomy","term"]
{{% page-kinds %}}
### Default destinations
### Default Destinations
When taxonomies are used---and [taxonomy templates] are provided---Hugo will automatically create both a page listing all the taxonomy's terms and individual pages with lists of content associated with each term. For example, a `categories` taxonomy declared in your configuration and used in your content front matter will create the following pages:
* A single page at `example.com/categories/` that lists all the [terms within the taxonomy]
* [Individual taxonomy list pages][taxonomy templates] (e.g., `/categories/development/`) for each of the terms that shows a listing of all pages marked as part of that taxonomy within any content file's [front matter]
## Configure taxonomies
## Configure Taxonomies
Custom taxonomies other than the [defaults](#default-taxonomies) must be defined in your [site configuration] before they can be used throughout the site. You need to provide both the plural and singular labels for each taxonomy. For example, `singular key = "plural value"` for TOML and `singular key: "plural value"` for YAML.
Custom taxonomies other than the [defaults](#default-taxonomies) must be defined in your [site config][config] before they can be used throughout the site. You need to provide both the plural and singular labels for each taxonomy. For example, `singular key = "plural value"` for TOML and `singular key: "plural value"` for YAML.
### Example: adding a custom taxonomy named "series"
### Example: Adding a custom taxonomy named "series"
{{% note %}}
While adding custom taxonomies, you need to put in the default taxonomies too, _if you want to keep them_.
@@ -120,9 +120,9 @@ While adding custom taxonomies, you need to put in the default taxonomies too, _
series = "series"
{{</ code-toggle >}}
### Example: removing default taxonomies
### Example: Removing default taxonomies
If you want to have just the default `tags` taxonomy, and remove the `categories` taxonomy for your site, you can do so by modifying the `taxonomies` value in your [site configuration].
If you want to have just the default `tags` taxonomy, and remove the `categories` taxonomy for your site, you can do so by modifying the `taxonomies` value in your [site config][config].
{{< code-toggle file="hugo" copy=false >}}
[taxonomies]
@@ -143,7 +143,7 @@ The configuration option `preserveTaxonomyNames` was removed in Hugo 0.55.
You can now use `.Page.Title` on the relevant taxonomy node to get the original value.
{{% /note %}}
## Add taxonomies to content
## Add Taxonomies to Content
Once a taxonomy is defined at the site level, any piece of content can be assigned to it, regardless of [content type] or [content section].
@@ -153,7 +153,7 @@ Assigning content to a taxonomy is done in the [front matter]. Simply create a v
If you would like the ability to quickly generate content files with preconfigured taxonomies or terms, read the docs on [Hugo archetypes](/content-management/archetypes/).
{{% /note %}}
### Example: front matter with taxonomies
### Example: Front Matter with Taxonomies
{{< code-toggle file="content/example.md" fm=true copy=false >}}
title = "Hugo: A fast and flexible static site generator"
@@ -164,13 +164,13 @@ slug = "hugo"
project_url = "https://github.com/gohugoio/hugo"
{{</ code-toggle >}}
## Order taxonomies
## Order Taxonomies
A content file can assign weight for each of its associate taxonomies. Taxonomic weight can be used for sorting or ordering content in [taxonomy list templates] and is declared in a content file's [front matter]. The convention for declaring taxonomic weight is `taxonomyname_weight`.
The following show a piece of content that has a weight of 22, which can be used for ordering purposes when rendering the pages assigned to the "a", "b" and "c" values of the `tags` taxonomy. It has also been assigned the weight of 44 when rendering the "d" category page.
### Example: taxonomic `weight`
### Example: Taxonomic `weight`
{{< code-toggle copy=false >}}
title = "foo"
@@ -186,7 +186,7 @@ By using taxonomic weight, the same piece of content can appear in different pos
Currently taxonomies only support the [default `weight => date` ordering of list content](/templates/lists/#default-weight--date--linktitle--filepath). For more information, see the documentation on [taxonomy templates](/templates/taxonomy-templates/).
{{% /note %}}
## Add custom metadata to a taxonomy or term
## Add custom metadata to a Taxonomy or Term
If you need to add custom metadata to your taxonomy terms, you will need to create a page for that term at `/content/<TAXONOMY>/<TERM>/_index.md` and add your metadata in its front matter. Continuing with our 'Actors' example, let's say you want to add a Wikipedia page link to each actor. Your terms pages would be something like this:
@@ -203,4 +203,4 @@ wikipedia: "https://en.wikipedia.org/wiki/Bruce_Willis"
[taxonomy list templates]: /templates/taxonomy-templates/#taxonomy-list-templates
[taxonomy templates]: /templates/taxonomy-templates/
[terms within the taxonomy]: /templates/taxonomy-templates/#taxonomy-terms-templates "See how to order terms associated with a taxonomy"
[configuration]: /getting-started/configuration/
[config]: /getting-started/configuration/
+4 -4
View File
@@ -1,5 +1,5 @@
---
title: Table of contents
title: Table of Contents
description: Hugo can automatically parse Markdown content and create a Table of Contents you can use in your templates.
categories: [content management]
keywords: [table of contents, toc]
@@ -44,7 +44,7 @@ Hugo will take this Markdown and create a table of contents from `## Introductio
The built-in `.TableOfContents` variables outputs a `<nav id="TableOfContents">` element with a child `<ul>`, whose child `<li>` elements begin with appropriate HTML headings. See [the available settings](/getting-started/configuration-markup/#table-of-contents) to configure what heading levels you want to include in TOC.
## Template example: basic TOC
## Template Example: Basic TOC
The following is an example of a very basic [single page template]:
@@ -64,7 +64,7 @@ The following is an example of a very basic [single page template]:
{{ end }}
{{< /code >}}
## Template example: TOC partial
## Template Example: TOC Partial
The following is a [partial template][partials] that adds slightly more logic for page-level control over your table of contents. It assumes you are using a `toc` field in your content's [front matter] that, unless specifically set to `false`, will add a TOC to any page with a `.WordCount` (see [Page Variables][pagevars]) greater than 400. This example also demonstrates how to use [conditionals] in your templating:
@@ -92,7 +92,7 @@ In the header of your content file, specify the AsciiDoc TOC directives necessar
```asciidoc
// <!-- Your front matter up here -->
:toc:
// Set toclevels to be at least your hugo [markup.tableOfContents.endLevel] configuration key
// Set toclevels to be at least your hugo [markup.tableOfContents.endLevel] config key
:toclevels: 4
== Introduction
+2 -2
View File
@@ -1,5 +1,5 @@
---
title: Content types
title: Content Types
description: Hugo is built around content organized in sections.
categories: [content management]
keywords: [lists, sections, content types, types, organization]
@@ -16,5 +16,5 @@ A **content type** is a way to organize your content. Hugo resolves the content
A content type is used to
- Determine how the content is rendered. See [Template Lookup Order](/templates/lookup-order/) and [Content Views](/templates/views) for more.
- Determine how the content is rendered. See [Template Lookup Order](/templates/lookup-order/) and [Content Views](https://gohugo.io/templates/views) for more.
- Determine which [archetype](/content-management/archetypes/) template to use for new content.
+5 -5
View File
@@ -1,5 +1,5 @@
---
title: URL management
title: URL Management
description: Control the structure and appearance of URLs through front matter entries and settings in your site configuration.
categories: [content management]
keywords: [aliases,redirects,permalinks,urls]
@@ -93,7 +93,7 @@ In your site configuration, define a URL pattern for each top-level section. Eac
Front matter `url` values override the URL patterns defined in the `permalinks` section of your site configuration.
[page kind]: /templates/section-templates/#page-kinds
[page kind]: https://gohugo.io/templates/section-templates/#page-kinds
#### Monolingual examples {#permalinks-monolingual-examples}
@@ -271,10 +271,10 @@ Use these tokens when defining the URL pattern. The `date` field in front matter
: the content's slug (or title if no slug is provided in the front matter)
`:slugorfilename`
: the content's slug (or file name if no slug is provided in the front matter)
: the content's slug (or filename if no slug is provided in the front matter)
`:filename`
: the content's file name (without extension)
: the content's filename (without extension)
For time-related values, you can also use the layout string components defined in Go's [time package]. For example:
@@ -383,7 +383,7 @@ In a multilingual site, use a directory-relative alias, or include the language
aliases = ['/de/posts/previous-file-name']
{{< /code-toggle >}}
### How aliases work
### How Aliases Work
Using the first example above, Hugo generates the following site structure:
+4 -5
View File
@@ -1,15 +1,14 @@
---
title: Contribute to the Hugo project
linkTitle: Overview
title: Contribute to the Hugo Project
linktitle: Contribute to Hugo
description: Contribute to Hugo development and documentation.
categories: [contribute]
keywords: []
menu:
docs:
identifier: contribute-overview
parent: contribute
weight: 10
weight: 10
weight: 01
weight: 01
aliases: [/tutorials/how-to-contribute-to-hugo/,/community/contributing/]
---
+12 -12
View File
@@ -1,14 +1,14 @@
---
title: Contribute to development
linkTitle: Development
title: Contribute to Hugo Development
linktitle: Development
description: Hugo relies heavily on contributions from the open source community.
categories: [contribute]
keywords: [dev,open source]
menu:
docs:
parent: contribute
weight: 20
weight: 20
weight: 10
weight: 10
toc: true
---
@@ -33,7 +33,7 @@ The installation of Go should take only a few minutes. You have more than one op
If you are having trouble following the installation guides for Go, check out [Go Bootcamp, which contains setups for every platform][gobootcamp] or reach out to the Hugo community in the [Hugo Discussion Forums][forums].
### Install Go from source
### Install Go From Source
[Download the latest stable version of Go][godl] and follow the official [Go installation guide][goinstall].
@@ -71,11 +71,11 @@ More experienced users can use the [Go Version Manager][gvm] (GVM). GVM allows y
GVM comes in especially handy if you follow the development of Hugo over a longer period of time. Future versions of Hugo will usually be compiled with the latest version of Go. Sooner or later, you will have to upgrade if you want to keep up.
## Create a GitHub account
## Create a GitHub Account
If you're going to contribute code, you'll need to have an account on GitHub. Go to [www.github.com/join](https://github.com/join) and set up a personal account.
## Install Git on your system
## Install Git on Your System
You will need to have Git installed on your computer to contribute to Hugo development. Teaching Git is outside the scope of the Hugo docs, but if you're looking for an excellent reference to learn the basics of Git, we recommend the [Git book][gitbook] if you are not sure where to begin. We will include short explanations of the Git commands in this document.
@@ -87,11 +87,11 @@ Move back to the terminal and check if Git is already installed. Type in `git ve
Finally, check again with `git version` if Git was installed successfully.
### Git graphical front ends
### Git Graphical Front Ends
There are several [GUI clients](https://git-scm.com/downloads/guis) that help you to operate Git. Not all are available for all operating systems and maybe differ in their usage. Because of this we will document how to use the command-line, since the commands are the same everywhere.
### Install Hub on your system (optional)
### Install Hub on Your System (Optional)
Hub is a great tool for working with GitHub. The main site for it is [hub.github.com](https://hub.github.com/). Feel free to install this little Git wrapper.
@@ -208,7 +208,7 @@ origin https://github.com/gohugoio/hugo (fetch)
origin https://github.com/gohugoio/hugo (push)
```
## The Hugo Git contribution workflow
## The Hugo Git Contribution Workflow
### Create a new branch
@@ -229,7 +229,7 @@ git checkout -b <BRANCH-NAME>
You can check on which branch you are with `git branch`. You should see a list of all local branches. The current branch is indicated with a little asterisk.
### Contribute to documentation
### Contribute to Documentation
Perhaps you want to start contributing to the Hugo docs. If so, you can ignore most of the following steps and focus on the `/docs` directory within your newly cloned repository. You can change directories into the Hugo docs using `cd docs`.
@@ -408,7 +408,7 @@ Thank you for reading through this contribution guide. Hopefully, we will see yo
Feel free to [open an issue][newissue] if you think you found a bug or you have a new idea to improve Hugo. We are happy to hear from you.
## Additional references for learning Git and Go
## Additional References for Learning Git and Go
* [Codecademy's Free "Learn Git" Course][codecademy] (Free)
* [Code School and GitHub's "Try Git" Tutorial][trygit] (Free)
+4 -4
View File
@@ -1,15 +1,15 @@
---
title: Contribute to documentation
linkTitle: Documentation
title: Contribute to the Hugo Docs
linktitle: Documentation
description: Documentation is an integral part of any open source project. The Hugo documentation is as much a work in progress as the source it attempts to cover.
categories: [contribute]
keywords: [docs,documentation,community, contribute]
menu:
docs:
parent: contribute
weight: 30
weight: 20
toc: true
weight: 30
weight: 20
aliases: [/contribute/docs/]
---
+5 -5
View File
@@ -1,14 +1,14 @@
---
title: Add your hugo theme to the showcase
linkTitle: Themes
title: Add Your Hugo Theme to the Showcase
linktitle: Themes
description: If you've built a Hugo theme and want to contribute back to the Hugo Community, share it with us.
categories: [contribute]
keywords: [contribute,themes,design]
menu:
docs:
parent: contribute
weight: 40
weight: 40
weight: 30
weight: 30
aliases: [/contribute/theme/]
toc: true
---
@@ -17,7 +17,7 @@ A collection of all themes created by the Hugo community, including screenshots
Another great site for Hugo themes is [jamstackthemes.dev/](https://jamstackthemes.dev/ssg/hugo/).
### Add your theme to the repository
### Add Your Theme to the Repo
In order to add your Hugo theme to [themes.gohugo.io] please [open a pull request in the theme repository](https://github.com/gohugoio/hugoThemesSiteBuilder). **Please make sure that you've read the theme submission guidelines in the [README](https://github.com/gohugoio/hugoThemesSiteBuilder/blob/main/README.md#hugo-themes) of the hugoThemesSiteBuilder repository.**
+3 -3
View File
@@ -1,11 +1,11 @@
---
title: Hugo Documentation
linkTitle: Hugo
linktitle: Hugo
description: Hugo is the world's fastest static website engine. It's written in Go (aka Golang) and developed by bep, spf13 and friends.
menu:
main:
weight: 1
weight: 1
weight: 01
weight: 01
layout: documentation-home
---
+4 -4
View File
@@ -37,15 +37,15 @@ And since `Page` also provides a `.GetPage` method, the above is the same as:
{{ end }}
```
## .GetPage and multilingual sites
## .GetPage and Multilingual Sites
The previous examples have used the full content file name to look up the post. Depending on how you have organized your content (whether you have the language code in the file name or not, e.g. `my-post.en.md`), you may want to do the lookup without extension. This will get you the current language's version of the page:
The previous examples have used the full content filename to look up the post. Depending on how you have organized your content (whether you have the language code in the file name or not, e.g. `my-post.en.md`), you may want to do the lookup without extension. This will get you the current language's version of the page:
```go-html-template
{{ with .Site.GetPage "/blog/my-post" }}{{ .Title }}{{ end }}
```
## .GetPage example
## .GetPage Example
This code snippet---in the form of a [partial template][partials]---allows you to do the following:
@@ -63,7 +63,7 @@ This code snippet---in the form of a [partial template][partials]---allows you t
</ul>
{{< /code >}}
## `.GetPage` on page bundles
## `.GetPage` on Page Bundles
If the page retrieved by `.GetPage` is a [Leaf Bundle][leaf_bundle], and you
need to get the nested _**page** resources_ in that, you will need to use the
+2 -5
View File
@@ -1,14 +1,11 @@
---
title: Functions
linkTitle: Overview
title: Functions Quick Reference
description: Comprehensive list of Hugo templating functions, including basic and advanced usage examples.
keywords: []
menu:
docs:
identifier: functions-overview
parent: functions
weight: 10
weight: 10
weight: 01
aliases: [/layout/functions/,/templates/functions]
---
+1 -1
View File
@@ -20,7 +20,7 @@ The following shows `after` being used in conjunction with the [`slice` function
→ ["three", "four"]
```
## Example of `after` with `first`: 2nd&ndash;4th most recent articles
## Example of `after` with `first`: 2nd&ndash;4th Most Recent Articles
You can use `after` in combination with the [`first` function] and Hugo's [powerful sorting methods][lists]. Let's assume you have a list page at `example.com/articles`. You have 10 articles, but you want your templating for the [list/section page] to show only two rows:
+2 -2
View File
@@ -1,6 +1,6 @@
---
title: anchorize
description: Takes a string and sanitizes it the same way as the [`defaultMarkdownHandler`](/getting-started/configuration-markup#configure-markup) does for markdown headers.
description: Takes a string and sanitizes it the same way as the [`defaultMarkdownHandler`](https://gohugo.io/getting-started/configuration-markup#configure-markup) does for markdown headers.
categories: [functions]
menu:
docs:
@@ -10,7 +10,7 @@ signature: ["anchorize INPUT"]
relatedfuncs: [humanize]
---
If [Goldmark](/getting-started/configuration-markup#goldmark) is set as `defaultMarkdownHandler`, the sanitizing logic adheres to the setting [`markup.goldmark.parser.autoHeadingIDType`](/getting-started/configuration-markup#goldmark).
If [Goldmark](https://gohugo.io/getting-started/configuration-markup#goldmark) is set as `defaultMarkdownHandler`, the sanitizing logic adheres to the setting [`markup.goldmark.parser.autoHeadingIDType`](https://gohugo.io/getting-started/configuration-markup#goldmark).
Since the `defaultMarkdownHandler` and this template function use the same sanitizing logic, you can use the latter to determine the ID of a header for linking with anchor tags.
+1 -1
View File
@@ -1,6 +1,6 @@
---
title: apply
description: Given an array or slice, `apply` returns a new slice with a function applied over it.
description: Given a map, array, or slice, `apply` returns a new slice with a function applied over it.
categories: [functions]
menu:
docs:
+1 -1
View File
@@ -18,7 +18,7 @@ Note that the `key` can be either a `string` or a `string slice`. The latter is
{{ $m := dict (slice "a" "b" "c") "value" }}
```
## Example: using `dict` to pass multiple values to a `partial`
## Example: Using `dict` to pass multiple values to a `partial`
The partial below creates an SVG and expects `fill`, `height` and `width` from the caller:
+2 -2
View File
@@ -14,12 +14,12 @@ relatedfuncs: []
See the [Emoji cheat sheet][emojis] for available emoticons.
The `emojify` function can be called in your templates but not directly in your content files by default. For emojis in content files, set `enableEmoji` to `true` in your site's [configuration]. Then you can write emoji shorthand directly into your content files; e.g. <code>I :</code><code>heart</code><code>: Hugo!</code>:
The `emojify` function can be called in your templates but not directly in your content files by default. For emojis in content files, set `enableEmoji` to `true` in your site's [configuration][config]. Then you can write emoji shorthand directly into your content files; e.g. <code>I :</code><code>heart</code><code>: Hugo!</code>:
I :heart: Hugo!
[configuration]: /getting-started/configuration/
[config]: /getting-started/configuration/
[emojis]: https://www.webfx.com/tools/emoji-cheat-sheet/
[sc]: /templates/shortcode-templates/
[scsource]: https://github.com/gohugoio/hugo/tree/master/docs/layouts/shortcodes
+1 -1
View File
@@ -40,6 +40,6 @@ This will produce:
```
ERROR 2021/06/07 17:47:38 You should consider fixing this.
If you feel that this should not be logged as an ERROR, you can ignore it by adding this to your site configuration:
If you feel that this should not be logged as an ERROR, you can ignore it by adding this to your site config:
ignoreErrors = ["my-custom-error"]
```
+3 -3
View File
@@ -25,7 +25,7 @@ Assuming a key-value of `date: 2017-03-03` in a content file's front matter, you
For formatting *any* string representations of dates defined in your front matter, see the [`dateFormat` function][dateFormat], which will still leverage the Go layout string explained below but uses a slightly different syntax.
## Go's layout string
## Go's Layout String
Hugo templates [format your dates][time] via layout strings that point to a specific reference time:
@@ -42,7 +42,7 @@ Here is a visual explanation [taken directly from the Go docs][gdex]:
=> 1 2 3 4 5 6 -7
```
### Hugo date and time templating reference
### Hugo Date and Time Templating Reference
The following examples show the layout string followed by the rendered output.
@@ -84,7 +84,7 @@ date: 2017-03-03T14:15:59-06:00
More examples can be found in Go's [documentation for the time package][timeconst].
### Cardinal s
### Cardinal Numbers and Ordinal Abbreviations
Spelled-out cardinal numbers (e.g. "one", "two", and "three") are not currently supported.
+1
View File
@@ -1,5 +1,6 @@
---
title: hasprefix
linktitle: hasPrefix
description: Tests whether a string begins with prefix.
date: 2017-02-01
publishdate: 2017-02-01
+2 -2
View File
@@ -1,6 +1,6 @@
---
title: hassuffix
linkTitle: hasSuffix
linktitle: hasSuffix
description: Tests whether a string ends with suffix.
date: 2023-03-01
publishdate: 2023-03-01
@@ -18,4 +18,4 @@ deprecated: false
aliases: []
---
* `{{ hasSuffix "Hugo" "go" }}` → true
* `{{ hasSuffix "Hugo" "go" }}` → true
+2 -2
View File
@@ -91,8 +91,8 @@ Instead of specifying both `lineNos` and `lineNumbersInTable`, you can use the f
{{ $input := `echo "Hello World!"` }}
{{ $lang := "bash" }}
{{ $options := dict "lineNos" "table" "style" "dracula" }}
{{ transform.Highlight $input $lang $options }}
{{ $options := slice "lineNos=table" "style=dracula" }}
{{ transform.Highlight $input $lang (delimit $options ",") }}
```
[Chroma]: https://github.com/alecthomas/chroma
+1 -1
View File
@@ -1,5 +1,5 @@
---
title: Image filters
title: Image Filters
description: The images namespace provides a list of filters and other image related functions.
categories: [functions]
aliases: [/functions/imageconfig/]
+1 -1
View File
@@ -37,7 +37,7 @@ You may write multiple indices as a slice:
{{ index $map $slice }} => 20
```
## Example: load data from a path based on front matter parameters
## Example: Load Data from a Path Based on Front Matter Params
Assume you want to add a `location = ""` field to your front matter for every article written in `content/vacations/`. You want to use this field to populate information about the location at the bottom of the article in your `single.html` template. You also have a directory in `data/locations/` that looks like the following:
+1 -1
View File
@@ -19,7 +19,7 @@ A useful example is to use it as `AND` filters when combined with where:
{{ $pages := $pages | intersect (where .Site.RegularPages "Params.images" "!=" nil) }}
```
The above fetches regular pages not of `page` or `about` type unless they are pinned. And finally, we exclude all pages with no `images` set in Page parameters.
The above fetches regular pages not of `page` or `about` type unless they are pinned. And finally, we exclude all pages with no `images` set in Page params.
See [union](/functions/union) for `OR`.
+1 -1
View File
@@ -17,6 +17,6 @@ Takes either a slice, array, or channel and an index or a map and a key as input
```
{{% note %}}
All site-level configuration keys are stored as lower case. Therefore, a `myParam` key-value set in your [site configuration file](/getting-started/configuration/) needs to be accessed with `{{ if isset .Site.Params "myparam" }}` and *not* with `{{ if isset .Site.Params "myParam" }}`. Note that you can still access the same configuration key with `.Site.Params.myParam` *or* `.Site.Params.myparam`, for example, when using [`with`](/functions/with).
All site-level configuration keys are stored as lower case. Therefore, a `myParam` key-value set in your [site configuration file](/getting-started/configuration/) needs to be accessed with `{{ if isset .Site.Params "myparam" }}` and *not* with `{{ if isset .Site.Params "myParam" }}`. Note that you can still access the same config key with `.Site.Params.myParam` *or* `.Site.Params.myparam`, for example, when using [`with`](/functions/with).
This restriction also applies when accessing page-level front matter keys from within [shortcodes](/content-management/shortcodes/).
{{% /note %}}
+21 -23
View File
@@ -11,26 +11,24 @@ signature: []
relatedfuncs: []
---
| Function | Description | Example |
|-----------------|-----------------------------------------------------------------------------|---------------------------------------------------|
| `add` | Adds two or more numbers. | `{{ add 12 3 2 }}` &rarr; `17` |
| | *If one of the numbers is a float, the result is a float.* | `{{ add 1.1 2 }}` &rarr; `3.1` |
| `sub` | Subtracts one or more numbers from the first number. | `{{ sub 12 3 2 }}` &rarr; `7` |
| | *If one of the numbers is a float, the result is a float.* | `{{ sub 3 2.5 }}` &rarr; `0.5` |
| `mul` | Multiplies two or more numbers. | `{{ mul 12 3 2 }}` &rarr; `72` |
| | *If one of the numbers is a float, the result is a float.* | `{{ mul 2 3.1 }}` &rarr; `6.2` |
| `div` | Divides the first number by one or more numbers. | `{{ div 12 3 2 }}` &rarr; `2` |
| | *If one of the numbers is a float, the result is a float.* | `{{ div 6 4.0 }}` &rarr; `1.5` |
| `mod` | Modulus of two integers. | `{{ mod 15 3 }}` &rarr; `0` |
| `modBool` | Boolean of modulus of two integers. Evaluates to `true` if result equals 0. | `{{ modBool 15 3 }}` &rarr; `true` |
| `math.Abs` | Returns the absolute value of the given number. | `{{ math.Abs -2.1 }}` &rarr; `2.1` |
| `math.Ceil` | Returns the least integer value greater than or equal to the given number. | `{{ math.Ceil 2.1 }}` &rarr; `3` |
| `math.Floor` | Returns the greatest integer value less than or equal to the given number. | `{{ math.Floor 1.9 }}` &rarr; `1` |
| `math.Log` | Returns the natural logarithm of the given number. | `{{ math.Log 42 }}` &rarr; `3.737` |
| `math.Max` | Returns the greater of all numbers. Accepts scalars, slices, or both. | `{{ math.Max 1 (slice 2 3) 4 }}` &rarr; `4` |
| `math.Min` | Returns the smaller of all numbers. Accepts scalars, slices, or both. | `{{ math.Min 1 (slice 2 3) 4 }}` &rarr; `1` |
| `math.Product` | Returns the product of all numbers. Accepts scalars, slices, or both. | `{{ math.Product 1 (slice 2 3) 4 }}` &rarr; `24` |
| `math.Pow` | Returns the first number raised to the power of the second number. | `{{ math.Pow 2 3 }}` &rarr; `8` |
| `math.Round` | Returns the nearest integer, rounding half away from zero. | `{{ math.Round 1.5 }}` &rarr; `2` |
| `math.Sqrt` | Returns the square root of the given number. | `{{ math.Sqrt 81 }}` &rarr; `9` |
| `math.Sum` | Returns the sum of all numbers. Accepts scalars, slices, or both. | `{{ math.Sum 1 (slice 2 3) 4 }}` &rarr; `10` |
| Function | Description | Example |
|--------------|-----------------------------------------------------------------------------|-------------------------------------|
| `add` | Adds two or more numbers. | `{{ add 12 3 2 }}` &rarr; `17` |
| | *If one of the numbers is a float, the result is a float.* | `{{ add 1.1 2 }}` &rarr; `3.1` |
| `sub` | Subtracts one or more numbers from the first number. | `{{ sub 12 3 2 }}` &rarr; `7` |
| | *If one of the numbers is a float, the result is a float.* | `{{ sub 3 2.5 }}` &rarr; `0.5` |
| `mul` | Multiplies two or more numbers. | `{{ mul 12 3 2 }}` &rarr; `72` |
| | *If one of the numbers is a float, the result is a float.* | `{{ mul 2 3.1 }}` &rarr; `6.2` |
| `div` | Divides the first number by one or more numbers. | `{{ div 12 3 2 }}` &rarr; `2` |
| | *If one of the numbers is a float, the result is a float.* | `{{ div 6 4.0 }}` &rarr; `1.5` |
| `mod` | Modulus of two integers. | `{{ mod 15 3 }}` &rarr; `0` |
| `modBool` | Boolean of modulus of two integers. Evaluates to `true` if result equals 0. | `{{ modBool 15 3 }}` &rarr; `true` |
| `math.Abs` | Returns the absolute value of the given number. | `{{ math.Abs -2.1 }}` &rarr; `2.1` |
| `math.Ceil` | Returns the least integer value greater than or equal to the given number. | `{{ math.Ceil 2.1 }}` &rarr; `3` |
| `math.Floor` | Returns the greatest integer value less than or equal to the given number. | `{{ math.Floor 1.9 }}` &rarr; `1` |
| `math.Log` | Returns the natural logarithm of the given number. | `{{ math.Log 42 }}` &rarr; `3.737` |
| `math.Max` | Returns the greater of two or more numbers. | `{{ math.Max 12 3 2 }}` &rarr; `12` |
| `math.Min` | Returns the smaller of two or more numbers. | `{{ math.Min 12 3 2 }}` &rarr; `2` |
| `math.Pow` | Returns the first number raised to the power of the second number. | `{{ math.Pow 2 3 }}` &rarr; `8` |
| `math.Round` | Returns the nearest integer, rounding half away from zero. | `{{ math.Round 1.5 }}` &rarr; `2` |
| `math.Sqrt` | Returns the square root of the given number. | `{{ math.Sqrt 81 }}` &rarr; `9` |
+1 -1
View File
@@ -1,6 +1,6 @@
---
title: readDir
description: Returns an array of FileInfo structures sorted by file name, one element for each directory entry.
description: Returns an array of FileInfo structures sorted by filename, one element for each directory entry.
categories: [functions]
menu:
docs:
+2 -6
View File
@@ -34,16 +34,12 @@ Will produce:
`ZgotmplZ` is a special value, inserted by Go's [template/html] package, that indicates that unsafe content reached a CSS or URL context.
To indicate that the HTML attribute is safe:
To override the safety check, use the `safeHTMLAttr` function:
```go-html-template
{{ range site.Menus.main }}
<a {{ printf "href=%q" .URL | safeHTMLAttr }}>{{ .Name }}</a>
{{ end }}
```
{{% note %}}
As demonstrated above, you must pass the HTML attribute name _and_ value through the function. Applying `safeHTMLAttr` to the attribute value has no effect.
{{% /note %}}
```
[template/html]: https://pkg.go.dev/html/template
+2 -2
View File
@@ -19,7 +19,7 @@ relatedfuncs: []
{{ mul 1000 (time "2016-05-28T10:30:00.00+10:00").Unix }} → 1464395400000, or Unix time in milliseconds
```
## Using locations
## Using Locations
The optional `TIMEZONE` parameter is a string that sets a default time zone (or more specific, the location, which represents the collection of time offsets in a geographical area) that is associated with the specified time value. If the time value has an explicit timezone or offset specified, it will take precedence over the `TIMEZONE` parameter.
@@ -33,7 +33,7 @@ If no `TIMEZONE` is set, the `timeZone` from site configuration will be used.
{{ time "2020-01-20" "America/Los_Angeles" }} → 2020-01-20 00:00:00 -0800 PST
```
## Example: Using `time` to get month index
## Example: Using `time` to get Month Index
The following example takes a UNIX timestamp---set as `utimestamp: "1489276800"` in a content's front matter---converts the timestamp (string) to an integer using the [`int` function][int], and then uses [`printf`] to convert the `Month` property of `time` into an index.
@@ -27,7 +27,7 @@ In both the above examples, you get a map you can work with:
The above prints `Hello Hugo`.
## CSV options
## CSV Options
Unmarshal with CSV as input has some options you can set:
@@ -61,7 +61,7 @@ To get the contents of `<title>` in the document below, you use `{{ .message.tit
The following example lists the items of an RSS feed:
```go-html-template
{{ with resources.GetRemote "https://example.com/rss.xml" | transform.Unmarshal }}
{{ with resources.Get "https://example.com/rss.xml" | transform.Unmarshal }}
{{ range .channel.item }}
<strong>{{ .title | plainify | htmlUnescape }}</strong><br />
<p>{{ .description | plainify | htmlUnescape }}</p>
+1 -1
View File
@@ -36,6 +36,6 @@ This is also very useful to use as `OR` filters when combined with where:
{{ $pages = $pages | intersect (where .Site.RegularPages "Params.images" "!=" nil) }}
```
The above fetches regular pages not of `page` or `about` type unless they are pinned. And finally, we exclude all pages with no `images` set in Page parameters.
The above fetches regular pages not of `page` or `about` type unless they are pinned. And finally, we exclude all pages with no `images` set in Page params.
See [intersect](/functions/intersect) for `AND`.

Some files were not shown because too many files have changed in this diff Show More