为了账号安全,请及时绑定邮箱和手机立即绑定

如何从已解析的模板中获取模板“操作”的地图或列表?

如何从已解析的模板中获取模板“操作”的地图或列表?

Go
HUH函数 2022-04-20 17:54:25
所以我想以某种方式将{{ .blahblah }}模板中定义的所有操作作为字符串切片。例如,如果我有这个模板:<h1>{{ .name }} {{ .age }}</h1>我希望能够得到[]string{"name", "age"}。假设模板具有方法func (t *Template) Fields() []string:t := template.New("cooltemplate").Parse(`<h1>{{ .name }} {{ .age }}</h1>`)if t.Fields() == []string{"name", "age"} {    fmt.Println("Yay, now I know what fields I can pass in!")    // Now lets pass in the name field that we just discovered.    _ = t.Execute(os.Stdout, map[string]string{"name": "Jack", "age":"120"})}有没有办法像这样检查已解析的模板?谢谢!
查看完整描述

3 回答

?
富国沪深

TA贡献1790条经验 获得超9个赞

前言:正如 Voker 所建议的,该Template.Tree字段“仅导出供 html/template 使用,应被所有其他客户端视为未导出”。


您不应该依赖这样的东西来为模板执行提供输入。您必须知道要执行的模板及其预期的数据。你不应该在运行时“探索”它来为它提供参数。


您从解析模板中获得的价值是template.Template(text/template或者html/template,它们具有相同的 API)。此模板将模板表示为类型树parse.Tree。文本模板包含的所有内容都存储在此树中的节点中,包括静态文本、动作等。


话虽如此,您可以遍历这棵树并查找标识访问字段或调用函数的此类操作的节点。节点的类型parse.Node具有Node.Type()返回其类型的方法。可能的类型在包中定义为常量,parse在类型旁边parse.NodeType,例如


const (

        NodeText    NodeType = iota // Plain text.

        NodeAction                  // A non-control action such as a field evaluation.

        NodeBool                    // A boolean constant.

        NodeChain                   // A sequence of field accesses.

        NodeCommand                 // An element of a pipeline.

        NodeDot                     // The cursor, dot.


        NodeField      // A field or method name.

        NodeIdentifier // An identifier; always a function name.

        NodeIf         // An if action.

        NodeList       // A list of Nodes.

        NodeNil        // An untyped nil constant.

        NodeNumber     // A numerical constant.

        NodePipe       // A pipeline of commands.

        NodeRange      // A range action.

        NodeString     // A string constant.

        NodeTemplate   // A template invocation action.

        NodeVariable   // A $ variable.

        NodeWith       // A with action.

)

因此,这里有一个示例程序,它递归地遍历模板树,并查找具有NodeAction类型的节点,即“非控制操作,例如字段评估”。


这个解决方案只是一个演示,一个概念证明,它不能处理所有情况。


func ListTemplFields(t *template.Template) []string {

    return listNodeFields(t.Tree.Root, nil)

}


func listNodeFields(node parse.Node, res []string) []string {

    if node.Type() == parse.NodeAction {

        res = append(res, node.String())

    }


    if ln, ok := node.(*parse.ListNode); ok {

        for _, n := range ln.Nodes {

            res = listNodeFields(n, res)

        }

    }

    return res

}

使用它的示例:


t := template.Must(template.New("cooltemplate").

    Parse(`<h1>{{ .name }} {{ .age }}</h1>`))

fmt.Println(ListTemplFields(t))

输出(在Go Playground上试试):


[{{.name}} {{.age}}]


查看完整回答
反对 回复 2022-04-20
?
繁花如伊

TA贡献2012条经验 获得超12个赞

回答进行了一个小优化,也许会有所帮助:)


func listNodeFieldsV2(node parse.Node) []string {

    var res []string

    if node.Type() == parse.NodeAction {

        res = append(res, node.String())

    }

    if ln, ok := node.(*parse.ListNode); ok {

        for _, n := range ln.Nodes {

            res = append(res, listNodeFieldsV2(n)...)

        }

    }

    return res

}


查看完整回答
反对 回复 2022-04-20
?
MMMHUHU

TA贡献1834条经验 获得超8个赞

我碰巧需要大致相同的代码。在我的用例中,我们允许用户在一侧创建模板,并输入map[string]string用于以不同形式呈现的变量。


这是我到目前为止提出的代码(受 icza 的回答启发):


// Extract the template vars required from *simple* templates.

// Only works for top level, plain variables. Returns all problematic parse.Node as errors.

func RequiredTemplateVars(t *template.Template) ([]string, []error) {

    var res []string

    var errors []error

    var ln *parse.ListNode

    ln = t.Tree.Root

Node:

    for _, n := range ln.Nodes {

        if nn, ok := n.(*parse.ActionNode); ok {

            p := nn.Pipe

            if len(p.Decl) > 0 {

                errors = append(errors, fmt.Errorf("Node %v not supported", n))

                continue Node

            }

            for _, c := range p.Cmds {

                if len(c.Args) != 1 {

                    errors = append(errors, fmt.Errorf("Node %v not supported", n))

                    continue Node

                }

                if a, ok := c.Args[0].(*parse.FieldNode); ok {

                    if len(a.Ident) != 1 {

                        errors = append(errors, fmt.Errorf("Node %v not supported", n))

                        continue Node

                    }

                    res = append(res, a.Ident[0])

                } else {

                    errors = append(errors, fmt.Errorf("Node %v not supported", n))

                    continue Node

                }


            }

        } else {

            if _, ok := n.(*parse.TextNode); !ok {

                errors = append(errors, fmt.Errorf("Node %v not supported", n))

                continue Node

            }

        }

    }

    return res, errors

}

https://play.golang.org/p/nH95B45jUmI


查看完整回答
反对 回复 2022-04-20
  • 3 回答
  • 0 关注
  • 127 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号