summaryrefslogtreecommitdiffstats
path: root/tpl/cast/cast_test.go
diff options
context:
space:
mode:
authorLucas Jenss <lucas@x3ro.de>2017-09-28 00:35:47 +0200
committerBjørn Erik Pedersen <bjorn.erik.pedersen@gmail.com>2017-09-28 16:53:18 +0200
commit57adc539fc98dcb6fba8070b9611b8bd545f6f7f (patch)
tree6460e7c9ef36c7e52212e3ee364f7f0fe2d0138f /tpl/cast/cast_test.go
parentb277cb33e4dfa7440fca3b7888026944ce056154 (diff)
tpl: Add float template function
Add a template function that allows conversion to float. This is useful, for example, when passing aspect ratios into templates, which tend to not be integers. Fixes #3307
Diffstat (limited to 'tpl/cast/cast_test.go')
-rw-r--r--tpl/cast/cast_test.go37
1 files changed, 37 insertions, 0 deletions
diff --git a/tpl/cast/cast_test.go b/tpl/cast/cast_test.go
index a5e0db2af..fc20934f8 100644
--- a/tpl/cast/cast_test.go
+++ b/tpl/cast/cast_test.go
@@ -81,3 +81,40 @@ func TestToString(t *testing.T) {
assert.Equal(t, test.expect, result, errMsg)
}
}
+
+func TestToFloat(t *testing.T) {
+ t.Parallel()
+
+ ns := New()
+
+ for i, test := range []struct {
+ v interface{}
+ expect interface{}
+ }{
+ {"1", 1.0},
+ {template.HTML("2"), 2.0},
+ {template.CSS("3"), 3.0},
+ {template.HTMLAttr("4"), 4.0},
+ {template.JS("-5.67"), -5.67},
+ {template.JSStr("6"), 6.0},
+ {"1.23", 1.23},
+ {"-1.23", -1.23},
+ {"0", 0.0},
+ {float64(2.12), 2.12},
+ {int64(123), 123.0},
+ {2, 2.0},
+ {t, false},
+ } {
+ errMsg := fmt.Sprintf("[%d] %v", i, test.v)
+
+ result, err := ns.ToFloat(test.v)
+
+ if b, ok := test.expect.(bool); ok && !b {
+ require.Error(t, err, errMsg)
+ continue
+ }
+
+ require.NoError(t, err, errMsg)
+ assert.Equal(t, test.expect, result, errMsg)
+ }
+}