github.com/kovansky/hugo@v0.92.3-0.20220224232819-63076e4ff19f/tpl/lang/init.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
    15  
    16  import (
    17  	"github.com/gohugoio/hugo/deps"
    18  	"github.com/gohugoio/hugo/langs"
    19  	"github.com/gohugoio/hugo/tpl/internal"
    20  )
    21  
    22  const name = "lang"
    23  
    24  func init() {
    25  	f := func(d *deps.Deps) *internal.TemplateFuncsNamespace {
    26  		ctx := New(d, langs.GetTranslator(d.Language))
    27  
    28  		ns := &internal.TemplateFuncsNamespace{
    29  			Name:    name,
    30  			Context: func(args ...interface{}) (interface{}, error) { return ctx, nil },
    31  		}
    32  
    33  		ns.AddMethodMapping(ctx.Translate,
    34  			[]string{"i18n", "T"},
    35  			[][2]string{},
    36  		)
    37  
    38  		ns.AddMethodMapping(ctx.FormatNumber,
    39  			nil,
    40  			[][2]string{
    41  				{`{{ 512.5032 | lang.FormatNumber 2 }}`, `512.50`},
    42  			},
    43  		)
    44  
    45  		ns.AddMethodMapping(ctx.FormatPercent,
    46  			nil,
    47  			[][2]string{
    48  				{`{{ 512.5032 | lang.FormatPercent 2 }}`, `512.50%`},
    49  			},
    50  		)
    51  
    52  		ns.AddMethodMapping(ctx.FormatCurrency,
    53  			nil,
    54  			[][2]string{
    55  				{`{{ 512.5032 | lang.FormatCurrency 2 "USD" }}`, `$512.50`},
    56  			},
    57  		)
    58  
    59  		ns.AddMethodMapping(ctx.FormatAccounting,
    60  			nil,
    61  			[][2]string{
    62  				{`{{ 512.5032 | lang.FormatAccounting 2 "NOK" }}`, `NOK512.50`},
    63  			},
    64  		)
    65  
    66  		ns.AddMethodMapping(ctx.FormatNumberCustom,
    67  			nil,
    68  			[][2]string{
    69  				{`{{ lang.FormatNumberCustom 2 12345.6789 }}`, `12,345.68`},
    70  				{`{{ lang.FormatNumberCustom 2 12345.6789 "- , ." }}`, `12.345,68`},
    71  				{`{{ lang.FormatNumberCustom 6 -12345.6789 "- ." }}`, `-12345.678900`},
    72  				{`{{ lang.FormatNumberCustom 0 -12345.6789 "- . ," }}`, `-12,346`},
    73  				{`{{ -98765.4321 | lang.FormatNumberCustom 2 }}`, `-98,765.43`},
    74  			},
    75  		)
    76  
    77  		return ns
    78  	}
    79  
    80  	internal.AddTemplateFuncsNamespace(f)
    81  }