go - 如何用空模板覆盖模板 block ?

标签 go go-templates

使用 text/html 我在基本模板中定义了一个包含默认内容的 block。在某些情况下,我希望这个 block 是空的,所以我想我可以重新定义它的名称并使其不包含任何内容:

{{ block "something" . }}
    <h1>Default content</h1>
{{ end }}

// later in a place that does not want "something" ...
{{ define "something" }}{{ end }}

Go 似乎以某种方式认为此定义为“零”,并且仍会呈现默认内容,除非我将任何非空白内容放入定义中。

我找到了 this issue on the Golang repoa Playground example 中很好地描述了同样的事情:

package main

import (
    "fmt"
    "os"
    "runtime"
    "text/template"
)

func main() {

    fmt.Printf("Version: %q\n", runtime.Version())

    t, err := template.New("master").Parse(`{{block "area51" .}}Original Content{{end}}`)
    if err != nil {
        panic(err)
    }
    t, err = t.New("other_template").Parse(`{{define "area51"}}{{end}}`)
    if err != nil {
        panic(err)
    }

    fmt.Printf("Output:\n")
    if err := t.ExecuteTemplate(os.Stdout, "master", nil); err != nil {
        panic(err)
    }

    fmt.Printf("\n")

}

奇怪的是,这个问题提到它已修复(如果我理解正确的话,它会出现在 1.8.1 中),但它对我不起作用,无论是 1.8.1+ 还是 1.9。

这是 Golang 中的错误还是方法有缺陷?我是否需要做任何不同的事情才能重新定义 block 以使其呈现为空?

最佳答案

这是预期的行为。这记录在 Template.Parse() :

Templates can be redefined in successive calls to Parse, before the first use of Execute on t or any associated template. A template definition with a body containing only white space and comments is considered empty and will not replace an existing template's body. This allows using Parse to add new named template definitions without overwriting the main template body.

所以你不能“删除”一个已经定义的模板(你不能将它的内容替换为空)。

如果您“有条件地”需要它,则使用 {{if}} 操作来决定是否调用模板。或者,您可以在模板中放置一个 {{if}},模板本身可以选择不呈现任何内容。在这种情况下,您必须确保传递控制模板呈现内容的正确参数。

附言如果您使用的是 HTML 模板,则应始终使用 html/template而不是 text/template ,因为前者提供与包 text/template 相同的接口(interface),但还提供上下文转义以生成 HTML 输出以防止代码注入(inject)。

关于go - 如何用空模板覆盖模板 block ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46174445/

相关文章:

html - 系统找不到试图解析模板的指定路径

Go template.ExecuteTemplate 包含 html

go - 使用 golang 在 gcp 中创建实例时添加启动脚本

google-app-engine - 如何在 golang 中在 google appengine 上构建 TCP 监听器或服务器?

go - 测量每个流的 gRPC 带宽

go - 如何转义模板的输出?

if-statement - Golang 模板变量 isset

go - 使用 Go 模板中的变量键访问映射值

go - 哪个更适合测试非有限 float IsNaN 或 IsInf?

Golang (cgo) - 任意 void* 接口(interface)