github.com/whatlly/hugo@v0.47.1/tpl/cast/cast.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 cast 15 16 import ( 17 "html/template" 18 19 _cast "github.com/spf13/cast" 20 ) 21 22 // New returns a new instance of the cast-namespaced template functions. 23 func New() *Namespace { 24 return &Namespace{} 25 } 26 27 // Namespace provides template functions for the "cast" namespace. 28 type Namespace struct { 29 } 30 31 // ToInt converts the given value to an int. 32 func (ns *Namespace) ToInt(v interface{}) (int, error) { 33 v = convertTemplateToString(v) 34 return _cast.ToIntE(v) 35 } 36 37 // ToString converts the given value to a string. 38 func (ns *Namespace) ToString(v interface{}) (string, error) { 39 return _cast.ToStringE(v) 40 } 41 42 // ToFloat converts the given value to a float. 43 func (ns *Namespace) ToFloat(v interface{}) (float64, error) { 44 v = convertTemplateToString(v) 45 return _cast.ToFloat64E(v) 46 } 47 48 func convertTemplateToString(v interface{}) interface{} { 49 switch vv := v.(type) { 50 case template.HTML: 51 v = string(vv) 52 case template.CSS: 53 v = string(vv) 54 case template.HTMLAttr: 55 v = string(vv) 56 case template.JS: 57 v = string(vv) 58 case template.JSStr: 59 v = string(vv) 60 } 61 return v 62 }