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 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?
  • ¥15 关于#vue.js#的问题:修改用户信息功能图片无法回显,数据库中只存了一张图片(相关搜索:字符串)
  • ¥15 texstudio的问题,
  • ¥15 spaceclaim模型变灰色