From 2f17f9378ad96c4a9f6d7d24b0776ed3a25a08a3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bj=C3=B8rn=20Erik=20Pedersen?= Date: Mon, 21 May 2018 17:47:52 +0200 Subject: [PATCH] Do not return error on .Get "class" and vice versa in shortcodes The current error handling makes parameter checking in shortcodes too verbose for no good reason. Fixes #4745 --- hugolib/shortcode.go | 13 ++++++++----- hugolib/shortcode_test.go | 9 +++------ 2 files changed, 11 insertions(+), 11 deletions(-) diff --git a/hugolib/shortcode.go b/hugolib/shortcode.go index b82c1b6c2..937a90956 100644 --- a/hugolib/shortcode.go +++ b/hugolib/shortcode.go @@ -85,7 +85,10 @@ func (scp *ShortcodeWithPage) Get(key interface{}) interface{} { switch key.(type) { case int64, int32, int16, int8, int: if reflect.TypeOf(scp.Params).Kind() == reflect.Map { - return "error: cannot access named params by position" + // We treat this as a non error, so people can do similar to + // {{ $myParam := .Get "myParam" | default .Get 0 }} + // Without having to do additional checks. + return nil } else if reflect.TypeOf(scp.Params).Kind() == reflect.Slice { idx := int(reflect.ValueOf(key).Int()) ln := reflect.ValueOf(scp.Params).Len() @@ -101,10 +104,10 @@ func (scp *ShortcodeWithPage) Get(key interface{}) interface{} { return "" } } else if reflect.TypeOf(scp.Params).Kind() == reflect.Slice { - if reflect.ValueOf(scp.Params).Len() == 1 && reflect.ValueOf(scp.Params).Index(0).String() == "" { - return nil - } - return "error: cannot access positional params by string name" + // We treat this as a non error, so people can do similar to + // {{ $myParam := .Get "myParam" | default .Get 0 }} + // Without having to do additional checks. + return nil } } diff --git a/hugolib/shortcode_test.go b/hugolib/shortcode_test.go index a32487477..a4c6ca20d 100644 --- a/hugolib/shortcode_test.go +++ b/hugolib/shortcode_test.go @@ -185,17 +185,14 @@ func TestNestedNamedMissingParam(t *testing.T) { func TestIsNamedParamsSC(t *testing.T) { t.Parallel() wt := func(tem tpl.TemplateHandler) error { - tem.AddTemplate("_internal/shortcodes/byposition.html", `
`) - tem.AddTemplate("_internal/shortcodes/byname.html", `
`) + tem.AddTemplate("_internal/shortcodes/bynameorposition.html", `{{ with .Get "id" }}Named: {{ . }}{{ else }}Pos: {{ .Get 0 }}{{ end }}`) tem.AddTemplate("_internal/shortcodes/ifnamedparams.html", `
`) return nil } CheckShortCodeMatch(t, `{{< ifnamedparams id="name" >}}`, `
`, wt) CheckShortCodeMatch(t, `{{< ifnamedparams position >}}`, `
`, wt) - CheckShortCodeMatch(t, `{{< byname id="name" >}}`, `
`, wt) - CheckShortCodeMatch(t, `{{< byname position >}}`, `
`, wt) - CheckShortCodeMatch(t, `{{< byposition position >}}`, `
`, wt) - CheckShortCodeMatch(t, `{{< byposition id="name" >}}`, `
`, wt) + CheckShortCodeMatch(t, `{{< bynameorposition id="name" >}}`, `Named: name`, wt) + CheckShortCodeMatch(t, `{{< bynameorposition position >}}`, `Pos: position`, wt) } func TestInnerSC(t *testing.T) {