shithub: hugo

Download patch

ref: 4fc67fe44a3c65fc7faaed21d5fa5bb5f87edf2c
parent: 47fdfd5196cd24a23b30afe1d88969ffb413ab59
author: Brendan Roy <[email protected]>
date: Sat Sep 30 16:00:19 EDT 2017

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

--- /dev/null
+++ b/docs/content/functions/errorf.md
@@ -1,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 }}
+```
--- a/tpl/fmt/fmt.go
+++ b/tpl/fmt/fmt.go
@@ -15,15 +15,17 @@
 
 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.
@@ -40,4 +42,9 @@
 // Println returns string representation of the passed arguments ending with a newline.
 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...)
 }
--- a/tpl/fmt/init.go
+++ b/tpl/fmt/init.go
@@ -50,8 +50,14 @@
 			},
 		)
 
-		return ns
+		ns.AddMethodMapping(ctx.Errorf,
+			[]string{"errorf"},
+			[][2]string{
+				{`{{ errorf "%s." "failed" }}`, `failed.`},
+			},
+		)
 
+		return ns
 	}
 
 	internal.AddTemplateFuncsNamespace(f)