从模板执行中获取值

huangapple go评论88阅读模式
英文:

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()
}

playground

你总是可以将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()
}

playground

英文:

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>

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

const tmpl = `Before: {{.Data}}{{.Set &quot;YY&quot;}}, after: {{.Data}}`

type CustomData struct {
	Data string
}

func (c *CustomData) Set(d string) string { // it has to return anything
	c.Data = d
	return &quot;&quot;
}

func main() {
	c := &amp;CustomData{&quot;XX&quot;}
	funcMap := template.FuncMap{
		&quot;Set&quot;: c.Set,
	}
	t, _ := template.New(&quot;test&quot;).Funcs(funcMap).Parse(tmpl) // don&#39;t ignore errors in real code
	t.Execute(os.Stdout, c)
	fmt.Println()
}

<kbd>playground</kbd>

huangapple
  • 本文由 发表于 2015年7月12日 01:31:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/31359904.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定