shithub: hugo

Download patch

ref: 3954160a21bcde7d4f4c077f9cc9daa610f3e29e
parent: 93c5774dd70b63c8b5e9268778a355c50b590bb6
author: Cameron Moore <[email protected]>
date: Tue May 9 16:24:23 EDT 2017

tpl/time: Support overlapping namespace and template func

Fixes #3421

--- a/tpl/time/init.go
+++ b/tpl/time/init.go
@@ -25,8 +25,26 @@
 		ctx := New()
 
 		ns := &internal.TemplateFuncsNamespace{
-			Name:    name,
-			Context: func() interface{} { return ctx },
+			Name: name,
+			Context: func(v ...interface{}) interface{} {
+				// Handle overlapping "time" namespace and func.
+				//
+				// If no args are passed to `time`, assume namespace usage and
+				// return namespace context.
+				//
+				// If args are passed, show a deprecation warning and attempt to
+				// simulate the old "as time" behavior.
+
+				if len(v) == 0 {
+					return ctx
+				}
+
+				t, err := ctx.AsTime(v[0])
+				if err != nil {
+					return err
+				}
+				return t
+			},
 		}
 
 		ns.AddMethodMapping(ctx.Format,
@@ -42,7 +60,7 @@
 		)
 
 		ns.AddMethodMapping(ctx.AsTime,
-			[]string{"asTime"}, // TODO(bep) handle duplicate
+			[]string{"asTime"},
 			[][2]string{
 				{`{{ (asTime "2015-01-21").Year }}`, `2015`},
 			},
--- a/tpl/time/init_test.go
+++ b/tpl/time/init_test.go
@@ -34,5 +34,5 @@
 	}
 
 	require.True(t, found)
-	require.IsType(t, &Namespace{}, ns.Context.(func() interface{})())
+	require.IsType(t, &Namespace{}, ns.Context.(func(v ...interface{}) interface{})())
 }