templates - go html/template 中的可选模板?

标签 templates go

给定一组模板,例如:

布局.tpl

<html>
<head>
<title>Some title</title>
{{template extracss}}
</head>
<body>
<h1>Page title</h1>
{{template content .}}
</body>
</html>

主页.tpl

{{define "content"}}
<p>page content goes here</p>
{{end}}

编辑.tpl

{{define "content"}}
<form>form content goes here</form>
{{end}}

{{define "extracss"}}<style>body{background:pink}</style>{{end}}

使用它来呈现模板:

func Render(w http.ResponseWriter, tmpname string, data interface{}) {

    t, err := template.ParseFiles("views/layout.tpl", "views/"+tmpname+".tpl")
    // parse error
    if err != nil {
        http.Error(w, err.Error(), http.StatusInternalServerError)
    }

    if err := t.Execute(w, data); err != nil {
        http.Error(w, err.Error(), http.StatusInternalServerError)
    }
}

edit.tpl 将正确呈现,因为它定义了“extracss”,home.tpl 不会,因为模板解析器正确地说“没有这样的模板“extracss””。

那么我将使用什么机制来允许使用“可选”模板?

有什么想法吗?

最佳答案

空定义有效:{{define "extracss"}}{{end}}。它可能不是 super 优雅,但很容易理解。

请注意,您不需要重复空定义。您可以将它们放入您的主模板中,并仅在需要时在包含的模板中重新定义它们。

关于templates - go html/template 中的可选模板?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15616785/

相关文章:

C++ 编译时迭代与 get 函数

amazon-web-services - 如何在main.go之外读取文件并使其在AWS Lambda上运行

regex - gorilla Mux 正则表达式

go - 如何通过q​​uery/cli/go获取BigQuery表的到期日期?

postgresql - go-gorm postgres 方言 : managing structs for jsonb insert and find to properly use json tags

c++ - 这个模板如何通过运行时递归实现编译时优化?

html - 来自 Jade 的 sendFile ('/index.html' ) 和 render ('index' ) 之间的区别

c++ - 目标文件中的显式模板代码生成

c++ - 我如何从模板中的指针获取类型?

go - "Exported type should have comment or be unexported"golang VS 代码