Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

parsing templates at compile time

Tags:

go

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 ?

like image 450
girodt Avatar asked Feb 18 '23 13:02

girodt


2 Answers

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)
}
like image 157
Nick Craig-Wood Avatar answered Feb 26 '23 22:02

Nick Craig-Wood


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

like image 32
jorelli Avatar answered Feb 26 '23 22:02

jorelli