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 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类