登录
首页 >  Golang >  Go问答

在 Go 模板中使用嵌套模板和变量

来源:stackoverflow

时间:2024-02-20 19:45:29 251浏览 收藏

最近发现不少小伙伴都对Golang很感兴趣,所以今天继续给大家介绍Golang相关的知识,本文《在 Go 模板中使用嵌套模板和变量》主要内容涉及到等等知识点,希望能帮到你!当然如果阅读本文时存在不同想法,可以在评论中表达,但是请勿使用过激的措辞~

问题内容

这个想法是为 go 模板定义一个变量,它也是一个使用变量的模板(嵌套模板),如下所示:

package main

import (
    "os"
    "text/template"
)

type Todo struct {
    Name        string
    Description string
    Subtemplate string
}

func main() {
    td := Todo{
        Name: "Test name",
        Description: "Test description",
        Subtemplate: "Subtemplate {{.Name}}",
    }

    t, err := template.New("todos").Parse("{{.Subtemplate}} You have a task named \"{{ .Name}}\" with description: \"{{ .Description}}\"")
    if err != nil {
        panic(err)
    }
    err = t.Execute(os.Stdout, td)
    if err != nil {
        panic(err)
    }
}

上面代码的结果是:

subtemplate {{.name}} 您有一个名为“测试名称”的任务,其描述为:“测试描述”

意味着子模板中的变量 .name 未解析(可能是设计上不可能的,需要某种递归调用)。有没有其他方法可以达到这个效果?

它也应该适用于使用 template.funcmap 定义的模板函数。谢谢。


正确答案


您可以注册一个解析字符串模板并执行它的函数。

该函数可能如下所示:

func exec(body string, data any) (string, error) {
    t, err := template.new("").parse(body)
    if err != nil {
        return "", err
    }
    buf := &strings.builder{}
    err = t.execute(buf, data)
    return buf.string(), err
}

您将模板正文文本和模板执行数据传递给它。它执行它并返回结果。

注册后,您可以从模板中这样调用它:

{{exec .subtemplate .}}

完整示例:

td := todo{
    name:        "test name",
    description: "test description",
    subtemplate: "subtemplate {{.name}}",
}

t, err := template.new("todos").funcs(template.funcmap{
    "exec": func(body string, data any) (string, error) {
        t, err := template.new("").parse(body)
        if err != nil {
            return "", err
        }
        buf := &strings.builder{}
        err = t.execute(buf, data)
        return buf.string(), err
    },
}).parse("{{exec .subtemplate .}} you have a task named \"{{ .name}}\" with description: \"{{ .description}}\"")
if err != nil {
    panic(err)
}
err = t.execute(os.stdout, td)
if err != nil {
    panic(err)
}

这将输出(在 go playground 上尝试):

Subtemplate Test name You have a task named "Test name" with description: "Test description"

请注意,如果子模板在运行时没有更改,您应该预先解析它并存储生成的模板(*template.template),以避免每次执行模板时都必须解析它。

今天关于《在 Go 模板中使用嵌套模板和变量》的内容介绍就到此结束,如果有什么疑问或者建议,可以在golang学习网公众号下多多回复交流;文中若有不正之处,也希望回复留言以告知!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>