From 4e07dfc9bb10dff42ce345feaae8d4979c290f9f Mon Sep 17 00:00:00 2001 From: Ian Byrd Date: Sat, 2 Sep 2017 02:39:48 +0300 Subject: [PATCH] Filter `random` added. Random returns a random item out of the input slice. --- filters.go | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/filters.go b/filters.go index 0091981..e660da1 100644 --- a/filters.go +++ b/filters.go @@ -3,6 +3,7 @@ package pongo2addons import ( "bytes" "fmt" + "math/rand" "regexp" "strings" "time" @@ -22,6 +23,7 @@ func init() { pongo2.RegisterFilter("filesizeformat", filterFilesizeformat) pongo2.RegisterFilter("truncatesentences", filterTruncatesentences) pongo2.RegisterFilter("truncatesentences_html", filterTruncatesentencesHTML) + pongo2.RegisterFilter("random", filterRandom) // Markup pongo2.RegisterFilter("markdown", filterMarkdown) @@ -218,6 +220,24 @@ func filterTruncatesentencesHTML(in *pongo2.Value, param *pongo2.Value) (*pongo2 return pongo2.AsSafeValue(newOutput.String()), nil } +func filterRandom(in *pongo2.Value, param *pongo2.Value) (*pongo2.Value, *pongo2.Error) { + if !in.CanSlice() { + return nil, &pongo2.Error { + Sender: "filter:random", + OrigError: error.New("input is not sliceable"), + } + } + + if in.Len() <= 0 { + return nil, &pongo2.Error { + Sender: "filter:random", + OrigError: error.New("input slice is empty"), + } + } + + return in.Index(rand.Intn(in.Len())), nil +} + func filterTimeuntilTimesince(in *pongo2.Value, param *pongo2.Value) (*pongo2.Value, *pongo2.Error) { basetime, isTime := in.Interface().(time.Time) if !isTime {