github.com/gohugoio/hugo@v0.88.1/tpl/lang/lang.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 lang provides template functions for content internationalization.
    15  package lang
    16  
    17  import (
    18  	"fmt"
    19  	"math"
    20  	"strconv"
    21  	"strings"
    22  
    23  	translators "github.com/gohugoio/localescompressed"
    24  	"github.com/gohugoio/locales"
    25  	"github.com/pkg/errors"
    26  
    27  	"github.com/gohugoio/hugo/deps"
    28  	"github.com/spf13/cast"
    29  )
    30  
    31  // New returns a new instance of the lang-namespaced template functions.
    32  func New(deps *deps.Deps, translator locales.Translator) *Namespace {
    33  	return &Namespace{
    34  		translator: translator,
    35  		deps:       deps,
    36  	}
    37  }
    38  
    39  // Namespace provides template functions for the "lang" namespace.
    40  type Namespace struct {
    41  	translator locales.Translator
    42  	deps       *deps.Deps
    43  }
    44  
    45  // Translate returns a translated string for id.
    46  func (ns *Namespace) Translate(id interface{}, args ...interface{}) (string, error) {
    47  	var templateData interface{}
    48  
    49  	if len(args) > 0 {
    50  		if len(args) > 1 {
    51  			return "", errors.Errorf("wrong number of arguments, expecting at most 2, got %d", len(args)+1)
    52  		}
    53  		templateData = args[0]
    54  	}
    55  
    56  	sid, err := cast.ToStringE(id)
    57  	if err != nil {
    58  		return "", nil
    59  	}
    60  
    61  	return ns.deps.Translate(sid, templateData), nil
    62  }
    63  
    64  // FormatNumber formats number with the given precision for the current language.
    65  func (ns *Namespace) FormatNumber(precision, number interface{}) (string, error) {
    66  	p, n, err := ns.castPrecisionNumber(precision, number)
    67  	if err != nil {
    68  		return "", err
    69  	}
    70  	return ns.translator.FmtNumber(n, p), nil
    71  }
    72  
    73  // FormatPercent formats number with the given precision for the current language.
    74  // Note that the number is assumed to be a percentage.
    75  func (ns *Namespace) FormatPercent(precision, number interface{}) (string, error) {
    76  	p, n, err := ns.castPrecisionNumber(precision, number)
    77  	if err != nil {
    78  		return "", err
    79  	}
    80  	return ns.translator.FmtPercent(n, p), nil
    81  }
    82  
    83  // FormatCurrency returns the currency reprecentation of number for the given currency and precision
    84  // for the current language.
    85  func (ns *Namespace) FormatCurrency(precision, currency, number interface{}) (string, error) {
    86  	p, n, err := ns.castPrecisionNumber(precision, number)
    87  	if err != nil {
    88  		return "", err
    89  	}
    90  	c := translators.GetCurrency(cast.ToString(currency))
    91  	if c < 0 {
    92  		return "", fmt.Errorf("unknown currency code: %q", currency)
    93  	}
    94  	return ns.translator.FmtCurrency(n, p, c), nil
    95  }
    96  
    97  // FormatAccounting returns the currency reprecentation of number for the given currency and precision
    98  // for the current language in accounting notation.
    99  func (ns *Namespace) FormatAccounting(precision, currency, number interface{}) (string, error) {
   100  	p, n, err := ns.castPrecisionNumber(precision, number)
   101  	if err != nil {
   102  		return "", err
   103  	}
   104  	c := translators.GetCurrency(cast.ToString(currency))
   105  	if c < 0 {
   106  		return "", fmt.Errorf("unknown currency code: %q", currency)
   107  	}
   108  	return ns.translator.FmtAccounting(n, p, c), nil
   109  }
   110  
   111  func (ns *Namespace) castPrecisionNumber(precision, number interface{}) (uint64, float64, error) {
   112  	p, err := cast.ToUint64E(precision)
   113  	if err != nil {
   114  		return 0, 0, err
   115  	}
   116  
   117  	// Sanity check.
   118  	if p > 20 {
   119  		return 0, 0, fmt.Errorf("invalid precision: %d", precision)
   120  	}
   121  
   122  	n, err := cast.ToFloat64E(number)
   123  	if err != nil {
   124  		return 0, 0, err
   125  	}
   126  	return p, n, nil
   127  }
   128  
   129  // FormatNumberCustom formats a number with the given precision using the
   130  // negative, decimal, and grouping options.  The `options`
   131  // parameter is a string consisting of `<negative> <decimal> <grouping>`.  The
   132  // default `options` value is `- . ,`.
   133  //
   134  // Note that numbers are rounded up at 5 or greater.
   135  // So, with precision set to 0, 1.5 becomes `2`, and 1.4 becomes `1`.
   136  //
   137  // For a simpler function that adapts to the current language, see FormatNumberCustom.
   138  func (ns *Namespace) FormatNumberCustom(precision, number interface{}, options ...interface{}) (string, error) {
   139  	prec, err := cast.ToIntE(precision)
   140  	if err != nil {
   141  		return "", err
   142  	}
   143  
   144  	n, err := cast.ToFloat64E(number)
   145  	if err != nil {
   146  		return "", err
   147  	}
   148  
   149  	var neg, dec, grp string
   150  
   151  	if len(options) == 0 {
   152  		// defaults
   153  		neg, dec, grp = "-", ".", ","
   154  	} else {
   155  		delim := " "
   156  
   157  		if len(options) == 2 {
   158  			// custom delimiter
   159  			s, err := cast.ToStringE(options[1])
   160  			if err != nil {
   161  				return "", nil
   162  			}
   163  
   164  			delim = s
   165  		}
   166  
   167  		s, err := cast.ToStringE(options[0])
   168  		if err != nil {
   169  			return "", nil
   170  		}
   171  
   172  		rs := strings.Split(s, delim)
   173  		switch len(rs) {
   174  		case 0:
   175  		case 1:
   176  			neg = rs[0]
   177  		case 2:
   178  			neg, dec = rs[0], rs[1]
   179  		case 3:
   180  			neg, dec, grp = rs[0], rs[1], rs[2]
   181  		default:
   182  			return "", errors.New("too many fields in options parameter to NumFmt")
   183  		}
   184  	}
   185  
   186  	exp := math.Pow(10.0, float64(prec))
   187  	r := math.Round(n*exp) / exp
   188  
   189  	// Logic from MIT Licensed github.com/gohugoio/locales/
   190  	// Original Copyright (c) 2016 Go Playground
   191  
   192  	s := strconv.FormatFloat(math.Abs(r), 'f', prec, 64)
   193  	L := len(s) + 2 + len(s[:len(s)-1-prec])/3
   194  
   195  	var count int
   196  	inWhole := prec == 0
   197  	b := make([]byte, 0, L)
   198  
   199  	for i := len(s) - 1; i >= 0; i-- {
   200  		if s[i] == '.' {
   201  			for j := len(dec) - 1; j >= 0; j-- {
   202  				b = append(b, dec[j])
   203  			}
   204  			inWhole = true
   205  			continue
   206  		}
   207  
   208  		if inWhole {
   209  			if count == 3 {
   210  				for j := len(grp) - 1; j >= 0; j-- {
   211  					b = append(b, grp[j])
   212  				}
   213  				count = 1
   214  			} else {
   215  				count++
   216  			}
   217  		}
   218  
   219  		b = append(b, s[i])
   220  	}
   221  
   222  	if n < 0 {
   223  		for j := len(neg) - 1; j >= 0; j-- {
   224  			b = append(b, neg[j])
   225  		}
   226  	}
   227  
   228  	// reverse
   229  	for i, j := 0, len(b)-1; i < j; i, j = i+1, j-1 {
   230  		b[i], b[j] = b[j], b[i]
   231  	}
   232  
   233  	return string(b), nil
   234  }
   235  
   236  // NumFmt is deprecated, use FormatNumberCustom.
   237  // We renamed this in Hugo 0.87.
   238  // Deprecated: Use FormatNumberCustom
   239  func (ns *Namespace) NumFmt(precision, number interface{}, options ...interface{}) (string, error) {
   240  	return ns.FormatNumberCustom(precision, number, options...)
   241  }
   242  
   243  type pagesLanguageMerger interface {
   244  	MergeByLanguageInterface(other interface{}) (interface{}, error)
   245  }
   246  
   247  // Merge creates a union of pages from two languages.
   248  func (ns *Namespace) Merge(p2, p1 interface{}) (interface{}, error) {
   249  	merger, ok := p1.(pagesLanguageMerger)
   250  	if !ok {
   251  		return nil, fmt.Errorf("language merge not supported for %T", p1)
   252  	}
   253  	return merger.MergeByLanguageInterface(p2)
   254  }