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 求螺旋焊缝的图像处理
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面
  • ¥15 itunes恢复数据最后一步发生错误
  • ¥15 关于#windows#的问题:2024年5月15日的win11更新后资源管理器没有地址栏了顶部的地址栏和文件搜索都消失了
  • ¥100 H5网页如何调用微信扫一扫功能?
  • ¥15 讲解电路图,付费求解