girodt
girodt

Reputation: 379

parsing templates at compile time

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 ?

Upvotes: 5

Views: 1940

Answers (2)

Nick Craig-Wood
Nick Craig-Wood

Reputation: 54117

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)
}

Upvotes: 7

jorelli
jorelli

Reputation: 8368

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

Upvotes: 2

Related Questions