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

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


{{define "test"}}

<html>

    <head>

        <title> test </title>

    </head>

    <body>

        <h1> Hello, world!</h1>

        {{template "doesnotexist"}}

    </body>

</html>

{{end}}

主程序


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 $ 


收到一只叮咚
浏览 73回答 1
1回答

元芳怎么了

template.ParseFiles()不报告丢失的模板,因为通常不是所有的模板都在一个步骤中被解析,并且报告丢失的模板(by&nbsp;template.ParseFiles())不允许这样做。可以使用来自多个来源的多个调用来解析模板。例如,如果您调用该Template.Parse()方法或您的模板,您可以向其添加更多模板:_, err = t.Parse(`{{define "doesnotexist"}}the missing piece{{end}}`)if err != nil {&nbsp; &nbsp; fmt.Printf("Parse failed: %v", err)&nbsp; &nbsp; return}上面的代码将添加缺失的部分,您的模板执行将成功并生成输出(在Go Playground上尝试):<html>&nbsp; &nbsp; <head>&nbsp; &nbsp; &nbsp; &nbsp; <title> test </title>&nbsp; &nbsp; </head>&nbsp; &nbsp; <body>&nbsp; &nbsp; &nbsp; &nbsp; <h1> Hello, world!</h1>&nbsp; &nbsp; &nbsp; &nbsp; the missing piece&nbsp; &nbsp; </body></html>更进一步,不需要解析和“呈现”所有模板为您提供了优化的可能性。可能存在“普通”用户永远不会使用的管理页面,并且仅当管理员用户启动或使用您的应用程序时才需要。在这种情况下,您可以通过不必解析管理页面(仅当/如果管理员用户使用您的应用程序)来加速启动和相同的内存。
打开App,查看更多内容
随时随地看视频慕课网APP