Golang pongo2 过滤器 returns 不正确的值
Golang pongo2 filter returns incorrect value
我创建了一个 pongo2
过滤器,它应该 return Absolute
传递给过滤器的参数值。但是,如果我将值作为参数传递,过滤器只有 return 的正确答案。但是,如果我直接传递值,它 return 是不正确的值。
我的问题是,如果我直接传递值而不是作为参数传递,为什么结果 return 不正确?
package main
import (
"fmt"
"math"
"github.com/flosch/pongo2"
"log"
)
func init() {
pongo2.RegisterFilter("abs", func(in *pongo2.Value, param *pongo2.Value) (*pongo2.Value, *pongo2.Error) {
if in.IsString() {
return pongo2.AsValue(math.Abs(in.Float())), nil
}
return pongo2.AsValue(math.Abs(in.Float())), nil
})
}
func correctWay() {
tpl, err := pongo2.FromString("Hello {{ val|abs }}!")
if err != nil {
log.Fatal(err)
}
// Now you can render the template with the given
// pongo2.Context how often you want to.
out, err := tpl.Execute(pongo2.Context{"val": -5})
if err != nil {
log.Fatal(err)
}
fmt.Println(out)
}
func incorrectWay() {
tpl, err := pongo2.FromString("Hello {{ -5|abs }}!")
if err != nil {
log.Fatal(err)
}
// Now you can render the template with the given
// pongo2.Context how often you want to.
out, err := tpl.Execute(pongo2.Context{})
if err != nil {
log.Fatal(err)
}
fmt.Println(out)
}
func main() {
correctWay()
incorrectWay()
}
我认为最简单的选择是将其作为字符串传递。
// This works:
tpl, err := pongo2.FromString("Hello {{ '-5'|abs }}!")
// prints Hello 5.000000!
我做了一些实验,最初我认为这是因为 Go 如何处理 templates 中的减号,但我认为不是这样。我不知道 pongo 在做什么,我很确定如果你传入 -5
只有 5
被传递给你注册的函数(将 fmt.Println(in.Float())
添加到闭包),然后当它被 Go 输出时被否定。这可能是一个错误 ♂️。无论哪种方式,它都适用于字符串。
我创建了一个 pongo2
过滤器,它应该 return Absolute
传递给过滤器的参数值。但是,如果我将值作为参数传递,过滤器只有 return 的正确答案。但是,如果我直接传递值,它 return 是不正确的值。
我的问题是,如果我直接传递值而不是作为参数传递,为什么结果 return 不正确?
package main
import (
"fmt"
"math"
"github.com/flosch/pongo2"
"log"
)
func init() {
pongo2.RegisterFilter("abs", func(in *pongo2.Value, param *pongo2.Value) (*pongo2.Value, *pongo2.Error) {
if in.IsString() {
return pongo2.AsValue(math.Abs(in.Float())), nil
}
return pongo2.AsValue(math.Abs(in.Float())), nil
})
}
func correctWay() {
tpl, err := pongo2.FromString("Hello {{ val|abs }}!")
if err != nil {
log.Fatal(err)
}
// Now you can render the template with the given
// pongo2.Context how often you want to.
out, err := tpl.Execute(pongo2.Context{"val": -5})
if err != nil {
log.Fatal(err)
}
fmt.Println(out)
}
func incorrectWay() {
tpl, err := pongo2.FromString("Hello {{ -5|abs }}!")
if err != nil {
log.Fatal(err)
}
// Now you can render the template with the given
// pongo2.Context how often you want to.
out, err := tpl.Execute(pongo2.Context{})
if err != nil {
log.Fatal(err)
}
fmt.Println(out)
}
func main() {
correctWay()
incorrectWay()
}
我认为最简单的选择是将其作为字符串传递。
// This works:
tpl, err := pongo2.FromString("Hello {{ '-5'|abs }}!")
// prints Hello 5.000000!
我做了一些实验,最初我认为这是因为 Go 如何处理 templates 中的减号,但我认为不是这样。我不知道 pongo 在做什么,我很确定如果你传入 -5
只有 5
被传递给你注册的函数(将 fmt.Println(in.Float())
添加到闭包),然后当它被 Go 输出时被否定。这可能是一个错误 ♂️。无论哪种方式,它都适用于字符串。