dsf5632 2015-12-03 05:50
浏览 105
已采纳

如何使用Go模板通过FuncMap解析html文件

I use following code to parse html template. It works well.

func test(w http.ResponseWriter, req *http.Request) {

    data := struct {A int B int }{A: 2, B: 3}

    t := template.New("test.html").Funcs(template.FuncMap{"add": add})

    t, err := t.ParseFiles("test.html")

    if err!=nil{
        log.Println(err)
    }
    t.Execute(w, data)
}

func add(a, b int) int {
    return a + b
}

and html template test.html.

<html>
<head>
    <title></title>
</head>
<body>
    <input type="text" value="{{add .A .B}}">
</body>
</html>

But when I move html file to another directory. Then use the following code. The output is always empty.

t := template.New("./templates/test.html").Funcs(template.FuncMap{"add": add})

t, err := t.ParseFiles("./templates/test.html")

Can anyone tell me what's wrong? Or html/template package can not be used like this?

  • 写回答

1条回答 默认 最新

  • douyeke2695 2015-12-03 07:01
    关注

    What's wrong is that your program (the html/template package) can't find the test.html file. When you specify relative paths (yours are relative), they are resolved to the current working directory.

    You have to make sure the html files/templates are in the right place. If you start your app with go run ... for example, relative paths are resolved to the folder you're in, that will be the working directory.

    This relative path: "./templates/test.html" will try to parse the file being in the templates subfolder of the current folder. Make sure it's there.

    Another option is to use absolute paths.

    And also another important note: Do not parse templates in your handler function! That runs to serve each incoming request. Instead parse them in the package init() functions once.

    More details on this:

    It takes too much time when using "template" package to generate a dynamic web page to client in golang

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

报告相同问题?

悬赏问题

  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题
  • ¥20 yolov5自定义Prune报错,如何解决?