英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论