英文:
Getting values from a template execution
问题
我有一个HTML模板,我通过传递一个map[string]string变量来执行它。模板使用这个变量来创建HTML输出,然后发送给客户端。
除了生成HTML之外,我还想使用同一个模板生成一些值,这些值将返回给主程序,这样我就可以在外部使用同一个文件来放置一些逻辑。
据我所知,不可能修改我传递给Execute的变量(类似于{{.output = "value"}}
)。
那么,我该如何从模板执行中获取多个输出值呢?
英文:
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
得分: 1
你实际上不需要传递一个funcmap,只需要传递结构体。
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()
}
你总是可以将FuncMap
传递给模板,这里有一个非常简单的例子:
const tmpl = `Before: {{.Data}}{{.Set "YY"}}, after: {{.Data}}`
type CustomData struct {
Data string
}
func (c *CustomData) Set(d string) string { // 必须返回任何值
c.Data = d
return ""
}
func main() {
c := &CustomData{"XX"}
funcMap := template.FuncMap{
"Set": c.Set,
}
t, _ := template.New("test").Funcs(funcMap).Parse(tmpl) // 在真实代码中不要忽略错误
t.Execute(os.Stdout, c)
fmt.Println()
}
英文:
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()
}
<strike>You can always pass a FuncMap
to the template, here's an extremely simple example: </strike>
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()
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论