【问题标题】:How to use go template to parse html files with FuncMap如何使用 Go 模板通过 FuncMap 解析 html 文件
【发布时间】:2015-12-03 16:25:58
【问题描述】:

我使用以下代码来解析 html 模板。效果很好。

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
}

和html模板test.html。

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

但是当我将 html 文件移动到另一个目录时。然后使用以下代码。输出始终为空。

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

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

谁能告诉我怎么了?还是不能这样使用html/template包?

【问题讨论】:

    标签: parsing templates dictionary go func


    【解决方案1】:

    问题是您的程序(html/template 包)找不到test.html 文件。当您指定相对路径时(您的路径是相对的),它们将被解析为当前工作目录。

    您必须确保 html 文件/模板位于正确的位置。例如,如果您使用go run ... 启动您的应用程序,则相对路径将解析为您所在的文件夹,这将是工作目录。

    此相对路径:"./templates/test.html" 将尝试解析当前文件夹的 templates 子文件夹中的文件。确保它在那里。

    另一种选择是使用绝对路径。

    还有一个重要的注意事项:不要在处理函数中解析模板!运行以服务每个传入的请求。而是在包init()函数中解析它们一次。

    更多细节:

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

    【讨论】:

    • 抱歉这个愚蠢的问题。因为我混合了template.New(name string)和t.ParseFiles(filenames...string)的参数。它应该是 template.New(filename string).
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-20
    • 1970-01-01
    相关资源
    最近更新 更多