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
This commit is contained in:
Bjørn Erik Pedersen
2019-09-29 14:51:51 +02:00
parent e073f4efb1
commit 329e88db1f
12 changed files with 202 additions and 53 deletions

View File

@@ -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+$`)
)