Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/templates/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Templates 如何从pongo模板调用Go函数_Templates_Go_Pongo2 - Fatal编程技术网

Templates 如何从pongo模板调用Go函数

Templates 如何从pongo模板调用Go函数,templates,go,pongo2,Templates,Go,Pongo2,我需要使用map的几个键创建JSON数据,并需要将其合并到生成的html中。我正在使用pongo2库,并希望编写自定义过滤器来实现相同的功能 <script> {{ CategoryMapping|MycustomFilter }} </script> 但我的错误率越来越低 src/util/TemplateFilters.go:10: cannot use GetCategoryJsonData (type func(*int, *int) (*string, *er

我需要使用map的几个键创建JSON数据,并需要将其合并到生成的html中。我正在使用pongo2库,并希望编写自定义过滤器来实现相同的功能

<script> {{ CategoryMapping|MycustomFilter }} </script>
但我的错误率越来越低

src/util/TemplateFilters.go:10: cannot use GetCategoryJsonData (type func(*int, *int) (*string, *error)) as type pongo2.FilterFunction in argument to pongo2.RegisterFilter
本人现附上以下文件—


我是新手,无法理解我在这里做错了什么。请为我提供同样的指导。

问题是您的筛选函数不接受或返回与pongo2所需类型匹配的正确类型。让我们浏览一下文档,看看他们想要什么

<script> {{ CategoryMapping|MycustomFilter }} </script>
首先,看看godoc for
RegisterFilterFunction
。上面说

func RegisterFilter(name string, fn FilterFunction)
这在
pongo2
包中,因此您应该将其理解为
RegisterFilter
是一个接受两个参数且不返回任何值的函数。第一个参数
name
为内置类型
string
,第二个参数
fn
为类型
pongo2.FilterFunction
。但是什么是
pongo2.FilterFunction
?好的,点击它,我们可以在文档中看到更进一步的内容

type FilterFunction func(in *Value, param *Value) (out *Value, err *Error)
在Go中,您可以基于任何其他类型(包括函数)创建自己的类型。因此,pongo2所做的是创建一个名为
FilterFunction
的命名类型,它是任何一个接受两个参数(类型均为
*pongo2.Value
)并返回两个值(类型之一为
*pongo2.Value
,类型之一为
*pongo2.Error

为了将这一切结合在一起,我们将采取以下措施:

package main

import (
    "fmt"
    "log"
    "strings"

    "github.com/flosch/pongo2"
)

func init() {
    pongo2.RegisterFilter("scream", Scream)
}

// Scream is a silly example of a filter function that upper cases strings
func Scream(in *pongo2.Value, param *pongo2.Value) (out *pongo2.Value, err *pongo2.Error) {
    if !in.IsString() {
        return nil, &pongo2.Error{
            ErrorMsg: "only strings should be sent to the scream filter",
        }
    }

    s := in.String()
    s = strings.ToUpper(s)

    return pongo2.AsValue(s), nil
}

func main() {
    tpl, err := pongo2.FromString("Hello {{ name|scream }}!")
    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{"name": "stack overflow"})
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println(out) // Output: Hello STACK OVERFLOW!
}

您的函数需要有签名
func(in*pongo2.Value,param*pongo2.Value)(out*pongo2.Value,err*pongo2.Error)
@jcdwlkr-我阅读了文档,但无法生成用例或真正的工作代码。如果你能给我一个样品,那将是非常有帮助的。