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.
15package cast
16
17import (
18	"html/template"
19
20	_cast "github.com/spf13/cast"
21)
22
23// New returns a new instance of the cast-namespaced template functions.
24func New() *Namespace {
25	return &Namespace{}
26}
27
28// Namespace provides template functions for the "cast" namespace.
29type Namespace struct {
30}
31
32// ToInt converts the given value to an int.
33func (ns *Namespace) ToInt(v interface{}) (int, error) {
34	v = convertTemplateToString(v)
35	return _cast.ToIntE(v)
36}
37
38// ToString converts the given value to a string.
39func (ns *Namespace) ToString(v interface{}) (string, error) {
40	return _cast.ToStringE(v)
41}
42
43// ToFloat converts the given value to a float.
44func (ns *Namespace) ToFloat(v interface{}) (float64, error) {
45	v = convertTemplateToString(v)
46	return _cast.ToFloat64E(v)
47}
48
49func convertTemplateToString(v interface{}) interface{} {
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}
64