github.com/linchen2chris/hugo@v0.0.0-20230307053224-cec209389705/tpl/time/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 time 15 16 import ( 17 "context" 18 "errors" 19 20 "github.com/gohugoio/hugo/deps" 21 "github.com/gohugoio/hugo/langs" 22 "github.com/gohugoio/hugo/tpl/internal" 23 ) 24 25 const name = "time" 26 27 func init() { 28 f := func(d *deps.Deps) *internal.TemplateFuncsNamespace { 29 if d.Language == nil { 30 panic("Language must be set") 31 } 32 ctx := New(langs.GetTimeFormatter(d.Language), langs.GetLocation(d.Language)) 33 34 ns := &internal.TemplateFuncsNamespace{ 35 Name: name, 36 Context: func(cctx context.Context, args ...any) (any, error) { 37 // Handle overlapping "time" namespace and func. 38 // 39 // If no args are passed to `time`, assume namespace usage and 40 // return namespace context. 41 // 42 // If args are passed, call AsTime(). 43 44 switch len(args) { 45 case 0: 46 return ctx, nil 47 case 1: 48 return ctx.AsTime(args[0]) 49 case 2: 50 return ctx.AsTime(args[0], args[1]) 51 52 // 3 or more arguments. Currently not supported. 53 default: 54 return nil, errors.New("Invalid arguments supplied to `time`. Refer to time documentation: https://gohugo.io/functions/time/") 55 } 56 }, 57 } 58 59 ns.AddMethodMapping(ctx.Format, 60 []string{"dateFormat"}, 61 [][2]string{ 62 {`dateFormat: {{ dateFormat "Monday, Jan 2, 2006" "2015-01-21" }}`, `dateFormat: Wednesday, Jan 21, 2015`}, 63 }, 64 ) 65 66 ns.AddMethodMapping(ctx.Now, 67 []string{"now"}, 68 [][2]string{}, 69 ) 70 71 ns.AddMethodMapping(ctx.AsTime, 72 nil, 73 [][2]string{ 74 {`{{ (time "2015-01-21").Year }}`, `2015`}, 75 }, 76 ) 77 78 ns.AddMethodMapping(ctx.Duration, 79 []string{"duration"}, 80 [][2]string{ 81 {`{{ mul 60 60 | duration "second" }}`, `1h0m0s`}, 82 }, 83 ) 84 85 ns.AddMethodMapping(ctx.ParseDuration, 86 nil, 87 [][2]string{ 88 {`{{ "1h12m10s" | time.ParseDuration }}`, `1h12m10s`}, 89 }, 90 ) 91 92 return ns 93 } 94 95 internal.AddTemplateFuncsNamespace(f) 96 }