tpl: Add errorf template function
authorBrendan Roy <br3ndanr@gmail.com>
Sat, 30 Sep 2017 10:00:19 +0000 (20:00 +1000)
committerBjørn Erik Pedersen <bjorn.erik.pedersen@gmail.com>
Tue, 3 Oct 2017 05:59:51 +0000 (07:59 +0200)
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

docs/content/functions/errorf.md [new file with mode: 0644]
tpl/fmt/fmt.go
tpl/fmt/init.go

diff --git a/docs/content/functions/errorf.md b/docs/content/functions/errorf.md
new file mode 100644 (file)
index 0000000..9105ff8
--- /dev/null
@@ -0,0 +1,26 @@
+---
+title: errorf
+linktitle: errorf
+description: Evaluates a format string and logs it to ERROR.
+date: 2017-09-30
+publishdate: 2017-09-30
+lastmod: 2017-09-30
+categories: [functions]
+menu:
+  docs:
+    parent: "functions"
+keywords: [strings, log, error]
+signature: ["errorf FORMAT INPUT"]
+workson: []
+hugoversion:
+relatedfuncs: [printf]
+deprecated: false
+aliases: []
+---
+
+`errorf` will evaluate a format string, then output the result to the ERROR log.
+This will also cause the build to fail.
+
+```
+{{ errorf "Something went horribly wrong! %s" err }}
+```
index 96695442eb32e4b2826b685cca9fbc3f1d38c5f0..96113a5983c9572b8983bf6f74c325e1ea918942 100644 (file)
@@ -15,15 +15,17 @@ package fmt
 
 import (
        _fmt "fmt"
+       "github.com/gohugoio/hugo/helpers"
 )
 
 // New returns a new instance of the fmt-namespaced template functions.
 func New() *Namespace {
-       return &Namespace{}
+       return &Namespace{helpers.NewDistinctErrorLogger()}
 }
 
 // Namespace provides template functions for the "fmt" namespace.
 type Namespace struct {
+       errorLogger *helpers.DistinctLogger
 }
 
 // Print returns string representation of the passed arguments.
@@ -41,3 +43,8 @@ func (ns *Namespace) Printf(format string, a ...interface{}) string {
 func (ns *Namespace) Println(a ...interface{}) string {
        return _fmt.Sprintln(a...)
 }
+
+func (ns *Namespace) Errorf(format string, a ...interface{}) string {
+       ns.errorLogger.Printf(format, a...)
+       return _fmt.Sprintf(format, a...)
+}
index a3398b86293f7a904ff3506c9f690511a8b91862..76c68957aaa4b26674672c015802e101c11a5f83 100644 (file)
@@ -50,8 +50,14 @@ func init() {
                        },
                )
 
-               return ns
+               ns.AddMethodMapping(ctx.Errorf,
+                       []string{"errorf"},
+                       [][2]string{
+                               {`{{ errorf "%s." "failed" }}`, `failed.`},
+                       },
+               )
 
+               return ns
        }
 
        internal.AddTemplateFuncsNamespace(f)