登录
首页 >  Golang >  Go问答

防止Go html/template中同名块被覆盖

来源:stackoverflow

时间:2024-04-28 09:54:32 152浏览 收藏

小伙伴们有没有觉得学习Golang很有意思?有意思就对了!今天就给大家带来《防止Go html/template中同名块被覆盖》,以下内容将会涉及到,若是在学习中对其中部分知识点有疑问,或许看了本文就能帮到你!

问题内容

我在使用 go 中的模板呈现正确的内容时遇到困难。

我有一个基本模板 (base.tmpl) 和 2 个子模板(a.tmplb.tmpl)。

// base.tmpl
{{ define "base" }}
  {{ template "header" . }}
  {{ template "content" . }}
  {{ template "footer" . }}
{{ end }}
// a.tmpl
{{ template "base" . }}
{{ define "content" }}
  this is a.tmpl
{{ end }}
// b.tmpl
{{ template "base" . }}
{{ define "content" }}
  this is b.tmpl
{{ end }}

执行 a.tmpl 时,将插入 b.tmpl 中内容块的内容。

例如,渲染 a.tmpl 会导致页面显示:

this is b.tmpl

我正在解析模板(见下文)并返回并将结果分配给变量 x 因此我可以调用 x.executetemplate(w, "a.tmpl", nil)

func parseTemplates() *template.Template {
    templ := template.New("")
    err := filepath.Walk("./templates", func(path string, info os.FileInfo, err error) error {
        if strings.Contains(path, ".tmpl") {
            _, err = templ.ParseFiles(path)
            if err != nil {
                log.Println(err)
            }
        }

        return err
    })

    if err != nil {
        panic(err)
    }

    return templ
}

我假设这是因为在解析模板时,go 将 b.tmpl 的内容块定义保留为最新的。

我想知道是否有一种方法可以在运行时解析所有模板并简单地调用我想要执行的模板,而不必每次执行页面时重新解析页眉、内容、页脚等。


正确答案


分别解析a和b的模板。

atmpl, err := template.ParseFiles("base.tmpl", "a.tmpl")
if err != nil { /* handle error */ }

btmpl, err := template.ParseFiles("base.tmpl", "b.tmpl")
if err != nil { /* handle error */ }

今天带大家了解了的相关知识,希望对你有所帮助;关于Golang的技术知识我们会一点点深入介绍,欢迎大家关注golang学习网公众号,一起学习编程~

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>