dtll2016 2015-07-08 08:28
浏览 43


I'm trying to write a template (using html/template) and passing it a struct that has some methods attached to it, many of which return multiple values. Is there any way of accessing these from within the template? I'd like to be able to do something like:

package main

import (

type Foo struct {
    Name string

func (f Foo) Baz() (int, int) {
    return 1, 5

const tmpl = `Name: {{.Name}}, Ints: {{$a, $b := .Baz}}{{$a}}, {{b}}`

func main() {

    f := Foo{"Foo"}

    t, err := template.New("test").Parse(tmpl)
    if err != nil {

    t.Execute(os.Stdout, f)


But obviously this doesn't work. Is there no way around it?

I've considered creating an anonymous struct in my code:

data := struct {
    a   int
    b   int
data.a, data.b = f.Baz()

And passing that in, but would much prefer to have something in the template. Any ideas? I also tried writing a wrapper function which I added to funcMaps but could never get that to work at all.

Thanks for any suggestions!

  • 写回答

3条回答 默认 最新

  • duanhao8540 2015-07-08 10:52

    You won't be able to call a function that returns two values in a template unless one of those values is an error. This is so that your template is guaranteed to work at runtime. There is a great answer that explains that here, if you're interested.

    To solve your problem you need to either 1) break your function into two separate getter functions that you can call in the appropriate place in your template; or 2) have your function return a simple struct with the values inside.

    I can't tell which would be better for you because I really have no idea what your implementation requires. Foo and Baz don't give many clues. ;)

    Here is a quick-n-dirty example of option one:

    type Foo struct {
        Name string
    func (f Foo) GetA() (int) {
        return 1
    func (f Foo) GetB() (int) {
        return 5

    And then modify the template accordingly:

    const tmpl = `Name: {{.Name}}, Ints: {{.GetA}}, {{.GetB}}`

    Hopefully this is of some help. :)

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



  • ¥15 做了个的二极管反向饱和电流测量电路,但是测试达不到效果
  • ¥15 树莓派启动AP热点传入数据
  • ¥15 multisim中关于74ls192n和DSWPK开关的问题(相关搜索:计数器)
  • ¥15 在误装Windows server2019 后如何利用Windows.old恢复?
  • ¥20 代码实现状态连接包过滤防火墙的设计与实现
  • ¥15 vscode的红色箭头爆红和has no default export报错
  • ¥15 关于#sql#的问题:#情况描述 在用vs对项目进行调试时,出现找不到网络路径,然后查看SQL配置工具,发现SQL服务显示远程调用过程失败(相关搜索:防火墙)
  • ¥15 eNSP中基于默认路由及浮动路由的公司与分部互联和校园网综合项目
  • ¥15 主要进行描述泥浆在管路不同区段泥浆的密度不相同,泥浆的密度有高有低,此时管路的摩阻分布需要怎么计算,(标签-matlab)
  • ¥40 通过编制程序计算圆管内层流充分发展对流换热,参数如图5-4,以及公式5-16所示,要求用表5-6对程序计算准确性进行验证