Skip to content

Commit 4fc67fe

Browse files
bmonbep
authored andcommitted
tpl: Add errorf template function
Add template function that will build a string from the given format string and arguments, then log it to ERROR. This has an intended side-effect of causing the build to fail, when executed. Resolves #3817
1 parent 47fdfd5 commit 4fc67fe

File tree

3 files changed

+41
-2
lines changed

3 files changed

+41
-2
lines changed

‎docs/content/functions/errorf.md‎

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
---
2+
title: errorf
3+
linktitle: errorf
4+
description: Evaluates a format string and logs it to ERROR.
5+
date: 2017-09-30
6+
publishdate: 2017-09-30
7+
lastmod: 2017-09-30
8+
categories: [functions]
9+
menu:
10+
docs:
11+
parent: "functions"
12+
keywords: [strings, log, error]
13+
signature: ["errorf FORMAT INPUT"]
14+
workson: []
15+
hugoversion:
16+
relatedfuncs: [printf]
17+
deprecated: false
18+
aliases: []
19+
---
20+
21+
`errorf` will evaluate a format string, then output the result to the ERROR log.
22+
This will also cause the build to fail.
23+
24+
```
25+
{{ errorf "Something went horribly wrong! %s" err }}
26+
```

‎tpl/fmt/fmt.go‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,15 +15,17 @@ package fmt
1515

1616
import (
1717
_fmt "fmt"
18+
"github.com/gohugoio/hugo/helpers"
1819
)
1920

2021
// New returns a new instance of the fmt-namespaced template functions.
2122
func New() *Namespace {
22-
return &Namespace{}
23+
return &Namespace{helpers.NewDistinctErrorLogger()}
2324
}
2425

2526
// Namespace provides template functions for the "fmt" namespace.
2627
type Namespace struct {
28+
errorLogger *helpers.DistinctLogger
2729
}
2830

2931
// Print returns string representation of the passed arguments.
@@ -41,3 +43,8 @@ func (ns *Namespace) Printf(format string, a ...interface{}) string {
4143
func (ns *Namespace) Println(a ...interface{}) string {
4244
return _fmt.Sprintln(a...)
4345
}
46+
47+
func (ns *Namespace) Errorf(format string, a ...interface{}) string {
48+
ns.errorLogger.Printf(format, a...)
49+
return _fmt.Sprintf(format, a...)
50+
}

‎tpl/fmt/init.go‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -50,8 +50,14 @@ func init() {
5050
},
5151
)
5252

53-
return ns
53+
ns.AddMethodMapping(ctx.Errorf,
54+
[]string{"errorf"},
55+
[][2]string{
56+
{`{{ errorf "%s." "failed" }}`, `failed.`},
57+
},
58+
)
5459

60+
return ns
5561
}
5662

5763
internal.AddTemplateFuncsNamespace(f)

0 commit comments

Comments
 (0)