【问题标题】:How to call Go function from pongo template如何从 pongo 模板调用 Go 函数
【发布时间】:2016-09-17 12:30:05
【问题描述】:

我需要使用少数地图键创建 JSON 数据,并且需要合并到生成的 html 中。我正在使用 pongo2 库并想编写自定义过滤器来实现相同的目的。

<script> {{ CategoryMapping|MycustomFilter }} </script>

并编码自定义过滤器,如下所示。

func init() {

    pongo2.RegisterFilter("superfilter", GetCategoryJsonData)


}

func GetCategoryJsonData(CatAttributeMapping *map[string]interface{}, param *int) (*string, *error) {
.....
}

但我遇到了错误。

src/util/TemplateFilters.go:10: cannot use GetCategoryJsonData (type func(*int, *int) (*string, *error)) as type pongo2.FilterFunction in argument to pongo2.RegisterFilter

我正在关注以下文档 - https://godoc.org/github.com/flosch/pongo2#FilterFunction

我是新手,无法理解我在这里做错了什么。请指导我。

【问题讨论】:

  • 你的函数需要有签名func(in *pongo2.Value, param *pongo2.Value) (out *pongo2.Value, err *pongo2.Error)
  • @jcdwlkr- 我阅读了文档,但无法制作用例或真正的工作代码。如果你能提供一个样本,那将有很大的帮助。

标签: templates go pongo2


【解决方案1】:

问题是您的过滤器函数不接受或返回正确的类型来匹配 pongo2 的要求。让我们浏览一下文档,看看他们想要什么。

首先,查看 RegisterFilterFunction 的 godoc。它说

func RegisterFilter(name string, fn FilterFunction)

这是在pongo2 包中,因此您应该将其阅读为RegisterFilter 是一个接受两个参数并且不返回任何值的函数。第一个参数name 是内置类型string,第二个参数fnpongo2.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!
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-07
    • 2021-12-07
    • 2021-04-25
    相关资源
    最近更新 更多