Skip to content

text/template: arbitrary template picked on empty blocks  #40186

@bep

Description

@bep

Ref. the documentation:

A block is shorthand for defining a template
{{define "name"}} T1 {{end}}
and then executing it in place
{{template "name" pipeline}}

The program below prints:

Not Empty: 
notempty1-overlay|
notempty2-block|
Empty: empty-foo|
Empty2:     |

The below is a common construct to create master/overlay constructs, and it's also common to leave the blocks empty and optional. I would expect Empty: empty-foo| to be Empty:| -- and not just pick an arbitrary template with the same name. I have added the Empty2: | to show that empty template defintions (e.g. whitespace only) works fine on its own.

package main

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

func main() {
	var (
		master = `
Not Empty: 
{{ block "notempty1" . }}notempty-block{{ end }}|
{{ block "notempty2" . }}notempty2-block{{ end }}|
Empty: {{ block "empty" . }}   {{ end }}|
Empty2: {{ template "empty2" . }}|`
		overlay = `{{ define "notempty1" }}notempty1-overlay{{ end }}`
	)

	templs := template.New("")
	templs.New("foo").Parse(`
{{ define "notempty1" }}notempty1-foo{{ end }}
{{ define "notempty2" }}notempty2-foo{{ end }}
{{ define "empty" }}empty-foo{{ end }}
{{ define "empty2" }}    {{ end }}

`)

	masterTmpl, err := templs.New("master").Parse(master)
	if err != nil {
		log.Fatal(err)
	}
	overlayTmpl, err := template.Must(masterTmpl.Clone()).Parse(overlay)
	if err != nil {
		log.Fatal(err)
	}

	if err := overlayTmpl.Execute(os.Stdout, ""); err != nil {
		log.Fatal(err)
	}

	fmt.Println()

}

Metadata

Metadata

Assignees

No one assigned

    Labels

    FrozenDueToAgeWaitingForInfoIssue is not actionable because of missing required information, which needs to be provided.

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions