diff options
author | Bjørn Erik Pedersen <bjorn.erik.pedersen@gmail.com> | 2019-09-29 14:51:51 +0200 |
---|---|---|
committer | Bjørn Erik Pedersen <bjorn.erik.pedersen@gmail.com> | 2019-09-29 23:22:41 +0200 |
commit | 329e88db1f6d043d32c7083570773dccfd4f11fc (patch) | |
tree | a4bab342aa28523be8c854ceb88fece17f634410 /parser/pageparser/item.go | |
parent | e073f4efb1345f6408000ef3f389873f8cf7179e (diff) |
Support typed bool, int and float in shortcode params
This means that you now can do:
{{< vidur 9KvBeKu false true 32 3.14 >}}
And the boolean and numeric values will be converted to `bool`, `int` and `float64`.
If you want these to be strings, they must be quoted:
{{< vidur 9KvBeKu "false" "true" "32" "3.14" >}}
Fixes #6371
Diffstat (limited to 'parser/pageparser/item.go')
-rw-r--r-- | parser/pageparser/item.go | 45 |
1 files changed, 42 insertions, 3 deletions
diff --git a/parser/pageparser/item.go b/parser/pageparser/item.go index 3877ee6d9..48003ee86 100644 --- a/parser/pageparser/item.go +++ b/parser/pageparser/item.go @@ -16,12 +16,15 @@ package pageparser import ( "bytes" "fmt" + "regexp" + "strconv" ) type Item struct { - Type ItemType - Pos int - Val []byte + Type ItemType + Pos int + Val []byte + isString bool } type Items []Item @@ -30,6 +33,36 @@ func (i Item) ValStr() string { return string(i.Val) } +func (i Item) ValTyped() interface{} { + str := i.ValStr() + if i.isString { + // A quoted value that is a string even if it looks like a number etc. + return str + } + + if boolRe.MatchString(str) { + return str == "true" + } + + if intRe.MatchString(str) { + num, err := strconv.Atoi(str) + if err != nil { + return str + } + return num + } + + if floatRe.MatchString(str) { + num, err := strconv.ParseFloat(str, 64) + if err != nil { + return str + } + return num + } + + return str +} + func (i Item) IsText() bool { return i.Type == tText } @@ -132,3 +165,9 @@ const ( // preserved for later - keywords come after this tKeywordMarker ) + +var ( + boolRe = regexp.MustCompile(`^(true$)|(false$)`) + intRe = regexp.MustCompile(`^[-+]?\d+$`) + floatRe = regexp.MustCompile(`^[-+]?\d*\.\d+$`) +) |