在编译时解析模板

huangapple go评论72阅读模式
英文:

parsing templates at compile time

问题

根据我的理解,Go模板是在运行时从给定的源代码中解析出来,以获取一个已编译的template.Template类型的版本。然后,这个已编译的版本会在一些数据上执行,以进行实际的模板处理。

但是我想知道:是否有可能在编译时解析模板?

英文:

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 ?

答案1

得分: 6

只需将它们设置为全局变量像这样。您仍然会在运行时解析模板,但立即解析,所以如果无法正确解析它们,二进制文件将在运行时立即失败。

package main

import (
	"fmt"
	"text/template"
)

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

func main() {
	fmt.Println("Template", t)
}
英文:

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

答案2

得分: 2

无法在编译时完成,但可以在运行时的main()函数之前通过在init函数中解析它们来完成解析。

英文:

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

huangapple
  • 本文由 发表于 2013年2月11日 18:09:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/14809950.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定