tpl: Extend merge to accept multiple parameters

Fixes #7595
This commit is contained in:
Cameron Moore
2020-08-27 21:34:45 -05:00
committed by Bjørn Erik Pedersen
parent f9ebaaed1b
commit 047af7cfe5
3 changed files with 106 additions and 65 deletions

View File

@@ -17,17 +17,35 @@ import (
"reflect"
"strings"
"github.com/gohugoio/hugo/common/maps"
"github.com/gohugoio/hugo/common/hreflect"
"github.com/gohugoio/hugo/common/maps"
"github.com/pkg/errors"
)
// Merge creates a copy of dst and merges src into it.
// Currently only maps supported. Key handling is case insensitive.
func (ns *Namespace) Merge(src, dst interface{}) (interface{}, error) {
// Merge creates a copy of the final parameter and merges the preceeding
// parameters into it in reverse order.
// Currently only maps are supported. Key handling is case insensitive.
func (ns *Namespace) Merge(params ...interface{}) (interface{}, error) {
if len(params) < 2 {
return nil, errors.New("merge requires at least two parameters")
}
var err error
result := params[len(params)-1]
for i := len(params) - 2; i >= 0; i-- {
result, err = ns.merge(params[i], result)
if err != nil {
return nil, err
}
}
return result, nil
}
// merge creates a copy of dst and merges src into it.
func (ns *Namespace) merge(src, dst interface{}) (interface{}, error) {
vdst, vsrc := reflect.ValueOf(dst), reflect.ValueOf(src)
if vdst.Kind() != reflect.Map {
@@ -60,14 +78,12 @@ func caseInsensitiveLookup(m, k reflect.Value) (reflect.Value, bool) {
if strings.EqualFold(k.String(), key.String()) {
return m.MapIndex(key), true
}
}
return reflect.Value{}, false
}
func mergeMap(dst, src reflect.Value) reflect.Value {
out := reflect.MakeMap(dst.Type())
// If the destination is Params, we must lower case all keys.