resource_helpers.go (1672B)
1 // Copyright 2019 The Hugo Authors. All rights reserved.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 // http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13
14 package resource
15
16 import (
17 "strings"
18 "time"
19
20 "github.com/gohugoio/hugo/helpers"
21
22 "github.com/spf13/cast"
23 )
24
25 // GetParam will return the param with the given key from the Resource,
26 // nil if not found.
27 func GetParam(r Resource, key string) any {
28 return getParam(r, key, false)
29 }
30
31 // GetParamToLower is the same as GetParam but it will lower case any string
32 // result, including string slices.
33 func GetParamToLower(r Resource, key string) any {
34 return getParam(r, key, true)
35 }
36
37 func getParam(r Resource, key string, stringToLower bool) any {
38 v := r.Params()[strings.ToLower(key)]
39
40 if v == nil {
41 return nil
42 }
43
44 switch val := v.(type) {
45 case bool:
46 return val
47 case string:
48 if stringToLower {
49 return strings.ToLower(val)
50 }
51 return val
52 case int64, int32, int16, int8, int:
53 return cast.ToInt(v)
54 case float64, float32:
55 return cast.ToFloat64(v)
56 case time.Time:
57 return val
58 case []string:
59 if stringToLower {
60 return helpers.SliceToLower(val)
61 }
62 return v
63 case map[string]any:
64 return v
65 case map[any]any:
66 return v
67 }
68
69 return nil
70 }