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 ( import (
"bytes" "bytes"
"fmt" "fmt"
"math/rand"
"regexp" "regexp"
"strings" "strings"
"time" "time"
@ -22,6 +23,7 @@ func init() {
pongo2.RegisterFilter("filesizeformat", filterFilesizeformat) pongo2.RegisterFilter("filesizeformat", filterFilesizeformat)
pongo2.RegisterFilter("truncatesentences", filterTruncatesentences) pongo2.RegisterFilter("truncatesentences", filterTruncatesentences)
pongo2.RegisterFilter("truncatesentences_html", filterTruncatesentencesHTML) pongo2.RegisterFilter("truncatesentences_html", filterTruncatesentencesHTML)
pongo2.RegisterFilter("random", filterRandom)
// Markup // Markup
pongo2.RegisterFilter("markdown", filterMarkdown) pongo2.RegisterFilter("markdown", filterMarkdown)
@ -218,6 +220,24 @@ func filterTruncatesentencesHTML(in *pongo2.Value, param *pongo2.Value) (*pongo2
return pongo2.AsSafeValue(newOutput.String()), nil 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) { func filterTimeuntilTimesince(in *pongo2.Value, param *pongo2.Value) (*pongo2.Value, *pongo2.Error) {
basetime, isTime := in.Interface().(time.Time) basetime, isTime := in.Interface().(time.Time)
if !isTime { if !isTime {