Filter random added.

Random returns a random item out of the input slice.
This commit is contained in:
Ian Byrd 2017-09-02 02:39:48 +03:00 committed by GitHub
parent ada12dc6c9
commit 4e07dfc9bb

View File

@ -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 {