4

In my understanding, go templates are parsed from a given source at runtime in order to get a compiled version of type template.Template. Then, the compiled version is executed on some data to do the actual templating.

But then I'm wondering : is it possible to parse a template at compile time ?

4

2 回答 2

6

Just make them global variables like this. You'll still parse the templates at run time but it will be immediately so the binary will fail as soon as you run it if it can't parse them properly.

package main

import (
    "fmt"
    "text/template"
)

var t = template.Must(template.New("name").Parse("text"))

func main() {
    fmt.Println("Template", t)
}
于 2013-02-11T17:28:05.743 回答
2

can't do it at compile time, but you can parse them at runtime before main() by parsing them inside the init function.

于 2013-02-11T15:28:40.123 回答