github.com/neohugo/neohugo@v0.123.8/tpl/inflect/inflect.go (about) 1 // Copyright 2017 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 inflect provides template functions for the inflection of words. 15 package inflect 16 17 import ( 18 "strconv" 19 "strings" 20 21 _inflect "github.com/gobuffalo/flect" 22 "github.com/spf13/cast" 23 ) 24 25 // New returns a new instance of the inflect-namespaced template functions. 26 func New() *Namespace { 27 return &Namespace{} 28 } 29 30 // Namespace provides template functions for the "inflect" namespace. 31 type Namespace struct{} 32 33 // Humanize returns the humanized form of v. 34 // 35 // If v is either an integer or a string containing an integer 36 // value, the behavior is to add the appropriate ordinal. 37 func (ns *Namespace) Humanize(v any) (string, error) { 38 word, err := cast.ToStringE(v) 39 if err != nil { 40 return "", err 41 } 42 43 if word == "" { 44 return "", nil 45 } 46 47 _, ok := v.(int) // original param was literal int value 48 _, err = strconv.Atoi(word) // original param was string containing an int value 49 if ok || err == nil { 50 return _inflect.Ordinalize(word), nil 51 } 52 53 str := _inflect.Humanize(word) 54 return _inflect.Humanize(strings.ToLower(str)), nil 55 } 56 57 // Pluralize returns the plural form of the single word in v. 58 func (ns *Namespace) Pluralize(v any) (string, error) { 59 word, err := cast.ToStringE(v) 60 if err != nil { 61 return "", err 62 } 63 64 return _inflect.Pluralize(word), nil 65 } 66 67 // Singularize returns the singular form of a single word in v. 68 func (ns *Namespace) Singularize(v any) (string, error) { 69 word, err := cast.ToStringE(v) 70 if err != nil { 71 return "", err 72 } 73 74 return _inflect.Singularize(word), nil 75 }