duanpu4143 2015-07-11 17:31
浏览 52
已采纳

从模板执行中获取值

I have a HTML template that I execute passing a map[string]string variable. The template uses the variable to create the HTML output that I send to clients.

In addition to producing the HTML, I would like to use the very same template to generate some values that are retured to the main program, so I can use the same file to put some logic externally.

As far as I know, it is not possible to modify the variable I pass to Execute (something like {{.output = "value"}}).

So how could I get multiple output values from a template Execution?

  • 写回答

1条回答 默认 最新

  • duanchi3109 2015-07-12 02:19
    关注

    You don't actually need to pass a funcmap, just pass the struct.

    var tmpl = template.Must(template.New("test").Parse(`Before: {{.Data}}{{.Set "YY"}}, after: {{.Data}}`))
    
    func main() {
        c := &CustomData{"XX"}
        tmpl.Execute(os.Stdout, c)
        fmt.Println()
    }
    

    <kbd>playground</kbd>

    You can always pass a FuncMap to the template, here's an extremely simple example:

    const tmpl = `Before: {{.Data}}{{.Set "YY"}}, after: {{.Data}}`
    
    type CustomData struct {
        Data string
    }
    
    func (c *CustomData) Set(d string) string { // it has to return anything
        c.Data = d
        return ""
    }
    
    func main() {
        c := &CustomData{"XX"}
        funcMap := template.FuncMap{
            "Set": c.Set,
        }
        t, _ := template.New("test").Funcs(funcMap).Parse(tmpl) // don't ignore errors in real code
        t.Execute(os.Stdout, c)
        fmt.Println()
    }
    

    <kbd>playground</kbd>

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径