github.com/whatlly/hugo@v0.47.1/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  	"github.com/gohugoio/hugo/deps"
    18  	"github.com/gohugoio/hugo/tpl/internal"
    19  )
    20  
    21  const name = "time"
    22  
    23  func init() {
    24  	f := func(d *deps.Deps) *internal.TemplateFuncsNamespace {
    25  		ctx := New()
    26  
    27  		ns := &internal.TemplateFuncsNamespace{
    28  			Name: name,
    29  			Context: func(args ...interface{}) interface{} {
    30  				// Handle overlapping "time" namespace and func.
    31  				//
    32  				// If no args are passed to `time`, assume namespace usage and
    33  				// return namespace context.
    34  				//
    35  				// If args are passed, call AsTime().
    36  
    37  				if len(args) == 0 {
    38  					return ctx
    39  				}
    40  
    41  				t, err := ctx.AsTime(args[0])
    42  				if err != nil {
    43  					return err
    44  				}
    45  				return t
    46  			},
    47  		}
    48  
    49  		ns.AddMethodMapping(ctx.Format,
    50  			[]string{"dateFormat"},
    51  			[][2]string{
    52  				{`dateFormat: {{ dateFormat "Monday, Jan 2, 2006" "2015-01-21" }}`, `dateFormat: Wednesday, Jan 21, 2015`},
    53  			},
    54  		)
    55  
    56  		ns.AddMethodMapping(ctx.Now,
    57  			[]string{"now"},
    58  			[][2]string{},
    59  		)
    60  
    61  		ns.AddMethodMapping(ctx.AsTime,
    62  			nil,
    63  			[][2]string{
    64  				{`{{ (time "2015-01-21").Year }}`, `2015`},
    65  			},
    66  		)
    67  
    68  		ns.AddMethodMapping(ctx.Duration,
    69  			[]string{"duration"},
    70  			[][2]string{
    71  				{`{{ mul 60 60 | duration "second" }}`, `1h0m0s`},
    72  			},
    73  		)
    74  
    75  		ns.AddMethodMapping(ctx.ParseDuration,
    76  			nil,
    77  			[][2]string{
    78  				{`{{ "1h12m10s" | time.ParseDuration }}`, `1h12m10s`},
    79  			},
    80  		)
    81  
    82  		return ns
    83  
    84  	}
    85  
    86  	internal.AddTemplateFuncsNamespace(f)
    87  }