首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Golang pongo2过滤器返回不正确的值

Golang pongo2过滤器返回不正确的值
EN

Stack Overflow用户
提问于 2021-04-21 15:07:31
回答 1查看 168关注 0票数 0

我创建了一个pongo2过滤器,它应该返回传递给过滤器的参数的Absolute值。但是,只有当我将值作为参数传递时,筛选器才返回正确的答案。但是,如果我直接传递这个值,它会返回不正确的值。

我的问题是,如果直接传递值而不是作为参数,它为什么不返回正确的结果?

代码语言:javascript
复制
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()
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-04-21 15:19:02

我认为最简单的选择是把它作为字符串传递。

代码语言:javascript
复制
// This works:
tpl, err := pongo2.FromString("Hello {{ '-5'|abs }}!")
// prints Hello 5.000000!

我做了一些实验,最初我以为是因为Go如何处理模板中的负号,但我不认为是这样的。我不知道pongo在做什么,我相当肯定,如果您传入-5,那么5只会传递给您注册的函数(将fmt.Println(in.Float())添加到闭包中),当它被Go输出时,它将被否定。这可能是一个bug‍♂️。不管是哪种方式,它都与字符串一起工作。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67198519

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档