| 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/common/hmaps" |
| 21 |
"github.com/gohugoio/hugo/helpers" |
| 22 |
"github.com/pelletier/go-toml/v2" |
| 23 |
|
| 24 |
"github.com/spf13/cast" |
| 25 |
) |
| 26 |
|
| 27 |
// GetParam will return the param with the given key from the Resource, |
| 28 |
// nil if not found. |
| 29 |
func GetParam(r Resource, key string) any { |
| 30 |
return getParam(r, key, false) |
| 31 |
} |
| 32 |
|
| 33 |
// GetParamToLower is the same as GetParam but it will lower case any string |
| 34 |
// result, including string slices. |
| 35 |
func GetParamToLower(r Resource, key string) any { |
| 36 |
return getParam(r, key, true) |
| 37 |
} |
| 38 |
|
| 39 |
func getParam(r Resource, key string, stringToLower bool) any { |
| 40 |
v, err := hmaps.GetNestedParam(key, ".", r.Params()) |
| 41 |
|
| 42 |
if v == nil || err != nil { |
| 43 |
return nil |
| 44 |
} |
| 45 |
|
| 46 |
switch val := v.(type) { |
| 47 |
case bool: |
| 48 |
return val |
| 49 |
case string: |
| 50 |
if stringToLower { |
| 51 |
return strings.ToLower(val) |
| 52 |
} |
| 53 |
return val |
| 54 |
case int64, int32, int16, int8, int: |
| 55 |
return cast.ToInt(v) |
| 56 |
case float64, float32: |
| 57 |
return cast.ToFloat64(v) |
| 58 |
case time.Time: |
| 59 |
return val |
| 60 |
case toml.LocalDate: |
| 61 |
return val.AsTime(time.UTC) |
| 62 |
case toml.LocalDateTime: |
| 63 |
return val.AsTime(time.UTC) |
| 64 |
case []string: |
| 65 |
if stringToLower { |
| 66 |
return helpers.SliceToLower(val) |
| 67 |
} |
| 68 |
return v |
| 69 |
case map[string]any: |
| 70 |
return v |
| 71 |
case map[any]any: |
| 72 |
return v |
| 73 |
} |
| 74 |
return nil |
| 75 |
} |