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