drlma06060 2014-01-29 06:52
浏览 397
已采纳

如何打印函数的返回值?

Here is my function definition which returns a string

"addClassIfActive": func(tab string, ctx *web.Context) string

I'm trying to print it like this:

<a href="/home/"{{ printf "%s" addClassIfActive "home" .Context }}>Home</a>

http response is getting terminated when I'm trying to print.

What am I doing wrong?

Returning a boolean, and then using if works, still I'm curious how to print string returned from a function

  • 写回答

2条回答 默认 最新

  • doubipeng1336 2014-01-29 07:23
    关注

    The problem you have is that "home" and .Context will be the 3:rd and 4:th argument of printf and not the arguments of addClassIfActive. The return value of addClassIfActive becomes the 2:nd argument for printf.

    But the solution is simple: you don't have to use printf to print.

    If your function just returns a string, you can simply print it by writing:

    {{addClassIfActive "home" .Context}}
    

    Full working example:

    package main
    
    import (
        "html/template"
        "os"
    )
    
    type Context struct {
        Active bool
    }
    
    var templateFuncs = template.FuncMap{
        "addClassIfActive": func(tab string, ctx *Context) string {
            if ctx.Active {
                return tab + " content"
            }
    
            // Return nothing
            return ""
        },
    }
    
    var htmlTemplate = `{{addClassIfActive "home" .Context}}`
    
    func main() {
        data := map[string]interface{}{
            "Context": &Context{true}, // Set to false will prevent addClassIfActive to print
        }
    
        // We create the template and register out template function
        t := template.New("t").Funcs(templateFuncs)
        t, err := t.Parse(htmlTemplate)
        if err != nil {
            panic(err)
        }
    
        err = t.Execute(os.Stdout, data)
        if err != nil {
            panic(err)
        }
    
    }
    

    Output:

    home content

    Playground

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

问题事件

  • 请回答用户的提问 7月27日

悬赏问题

  • ¥15 不同尺寸货物如何寻找合适的包装箱型谱
  • ¥15 求解 yolo算法问题
  • ¥15 虚拟机打包apk出现错误
  • ¥15 用visual studi code完成html页面
  • ¥15 聚类分析或者python进行数据分析
  • ¥15 三菱伺服电机按启动按钮有使能但不动作
  • ¥15 js,页面2返回页面1时定位进入的设备
  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝