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