How can I override a template block with an empty template?

Viewed 1555

Using text/html I define a block in my base template, containing default content. In some situations I would like this block to be empty, so I thought I could just re-define its name and make it contain nothing like:

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

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

Somehow Go seems to think that this definition is "Zero" and will still render the default content unless I put any non-whitespace content into the definition.

I found this issue on the Golang repo which describes the very same thing nicely in a 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")

}

Weirdly, the issue mention it is fixed (and landed in 1.8.1 if I understand it correctly), but it does not work for me, neither with 1.8.1+ nor 1.9.

Is this a bug in Golang or is the approach flawed? Do I need to do anything differently in order to re-define the block so that it renders empty?

1 Answers
Related