Skip to content

text/template: Not possible to "define" two inline templates with the same name #22392

@bep

Description

@bep

This is the behaviour on Go 1.9. I have not tested other Go versions.

The following:

package main

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

func main() {
	var (
		tpl1 = `{{define "T1"}}T1_1{{end}}TPL1:{{template "T1"}}`
		tpl2 = `{{define "T1"}}T1_2{{end}}TPL2:{{template "T1"}}`
	)

	var buf bytes.Buffer
	tmpl := template.New("")

	tmpl1, err := tmpl.New("tpl1").Parse(tpl1)
	if err != nil {
		log.Fatal(err)
	}
	tmpl2, err := tmpl.New("tpl2").Parse(tpl2)
	if err != nil {
		log.Fatal(err)
	}

	if err := tmpl1.Execute(&buf, nil); err != nil {
		log.Fatal(err)
	}

	fmt.Println(buf.String())

	buf.Reset()
	if err := tmpl2.Execute(&buf, nil); err != nil {
		log.Fatal(err)
	}

	fmt.Println(buf.String())

}

Prints:

TPL1:T1_2
TPL2:T1_2

Expected:

TPL1:T1_1
TPL2:T1_2

It looks like they are both put into the same namespace and the last one wins. I have read the documentation at https://golang.org/pkg/text/template/ 3 times and I cannot see that what's described there is what I get. And what I get is really confusing.

gohugoio/hugo#3996

Metadata

Metadata

Assignees

No one assigned

    Labels

    FrozenDueToAgeNeedsInvestigationSomeone must examine and confirm this is a valid issue and not a duplicate of an existing one.release-blocker

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions