diff options
author | Joe Mooring <[email protected]> | 2023-12-28 14:25:29 -0800 |
---|---|---|
committer | Bjørn Erik Pedersen <[email protected]> | 2023-12-29 19:37:27 +0100 |
commit | e40b9fbbcf28c07ad90ae1048e144888414074d7 (patch) | |
tree | cc2babd1851fa23c375c2e48beb45d6898b5ef1f /tpl | |
parent | 9cd8fbb3324cb58e06095167cbea952619dd3201 (diff) | |
download | hugo-e40b9fbbcf28c07ad90ae1048e144888414074d7.tar.gz hugo-e40b9fbbcf28c07ad90ae1048e144888414074d7.zip |
tpl/math: Add math.Rand template function
Closes #11833
Diffstat (limited to 'tpl')
-rw-r--r-- | tpl/math/init.go | 7 | ||||
-rw-r--r-- | tpl/math/math.go | 6 | ||||
-rw-r--r-- | tpl/tplimpl/template_funcs_test.go | 10 |
3 files changed, 17 insertions, 6 deletions
diff --git a/tpl/math/init.go b/tpl/math/init.go index 8596ff647..fa1367671 100644 --- a/tpl/math/init.go +++ b/tpl/math/init.go @@ -115,6 +115,13 @@ func init() { }, ) + ns.AddMethodMapping(ctx.Rand, + nil, + [][2]string{ + {"{{ math.Rand }}", "0.6312770459590062"}, + }, + ) + ns.AddMethodMapping(ctx.Round, nil, [][2]string{ diff --git a/tpl/math/math.go b/tpl/math/math.go index a921bd7ad..0f8db11e2 100644 --- a/tpl/math/math.go +++ b/tpl/math/math.go @@ -18,6 +18,7 @@ import ( "errors" "fmt" "math" + "math/rand" "reflect" "sync/atomic" @@ -157,6 +158,11 @@ func (ns *Namespace) Pow(n1, n2 any) (float64, error) { return math.Pow(af, bf), nil } +// Rand returns, as a float64, a pseudo-random number in the half-open interval [0.0,1.0). +func (ns *Namespace) Rand() float64 { + return rand.Float64() +} + // Round returns the integer nearest to n, rounding half away from zero. func (ns *Namespace) Round(n any) (float64, error) { xf, err := cast.ToFloat64E(n) diff --git a/tpl/tplimpl/template_funcs_test.go b/tpl/tplimpl/template_funcs_test.go index 9cc84934b..f1ab3d659 100644 --- a/tpl/tplimpl/template_funcs_test.go +++ b/tpl/tplimpl/template_funcs_test.go @@ -61,12 +61,10 @@ title: "**BatMan**" ns := nsf(d) for _, mm := range ns.MethodMappings { for _, example := range mm.Examples { - if strings.Contains(example[0], "errorf") { - // This will fail the build, so skip for now. - continue - } - if strings.Contains(example[0], "transform.XMLEscape") { - // This will fail the build, so skip for now. + // These will fail the build, so skip. + if strings.Contains(example[0], "errorf") || + strings.Contains(example[0], "transform.XMLEscape") || + strings.Contains(example[0], "math.Rand") { continue } templates = append(templates, example[0]) |