为什么 template.ParseFiles() 没有检测到这个错误?

Why doesn't template.ParseFiles() detect this error?

如果我在我的模板文件中指定了一个不存在的模板,错误不是由 ParseFiles() 而是由 ExecuteTemplate() 检测到的。人们会期望解析来检测任何丢失的模板。在解析过程中检测此类错误也可以提高性能。

{{define "test"}}
<html>
    <head>
        <title> test </title>
    </head>
    <body>
        <h1> Hello, world!</h1>
        {{template "doesnotexist"}}
    </body>
</html>
{{end}}

main.go

package main

import (
    "html/template"
    "os"
    "fmt"
)

func main() {
    t, err := template.ParseFiles("test.html")
    if err != nil {
        fmt.Printf("ParseFiles: %s\n", err)
        return
    }

    err = t.ExecuteTemplate(os.Stdout, "test", nil)
    if err != nil {
        fmt.Printf("ExecuteTemplate: %s\n", err)
    }
}

10:46:30 $ go run main.go 
ExecuteTemplate: html/template:test.html:8:19: no such template "doesnotexist"
10:46:31 $ 

template.ParseFiles() 不报告丢失的模板,因为通常不是所有的模板都在一个步骤中被解析,并且报告丢失的模板(template.ParseFiles())不允许这样做。

可以使用来自多个来源的多个调用来解析模板。

例如,如果您调用 Template.Parse() 方法或您的模板,您可以向其添加更多模板:

_, err = t.Parse(`{{define "doesnotexist"}}the missing piece{{end}}`)
if err != nil {
    fmt.Printf("Parse failed: %v", err)
    return
}

以上代码将添加缺失的部分,您的模板执行将成功并生成输出(在 Go Playground 上尝试):

<html>
    <head>
        <title> test </title>
    </head>
    <body>
        <h1> Hello, world!</h1>
        the missing piece
    </body>
</html>

更进一步,不需要解析和“呈现”所有模板,这为您提供了优化的可能性。可能存在“普通”用户永远不会使用的管理页面,并且仅当管理员用户启动或使用您的应用程序时才需要。在这种情况下,您可以通过不必解析管理页面(仅当/如果管理员用户使用您的应用程序)来加速启动和相同的内存。

查看相关: