获取当前模板名称?

Is it possible to access the name of current template in Golang text/html/template without passing it as a data element to the template?

Thanks!

I'm hoping this is what you meant (from http://golang.org/pkg/text/template/#Template.Name)

func (t *Template) Name() string

"Name returns the name of the template."

If you mean to access the template name from within the template, I can only think to either add a function to the template.FuncMap, or, as you suggested to add the name as a data element.

The first would probably look something like:

var t = template.Must(template.New("page.html").ParseFiles("page.html"))
t.Funcs(template.FuncMap{"name": fmt.Sprint(t.Name())})

but I can't get it to work in the quick time I've messed about with it. Hopefully it might help point you in the right direction.

It would probably be easier in the long run just to add the name as a data element.

EDIT: In case anyone wants to know how to do it using template.FuncMap, it's basically a matter of defining the function after you create the template, then adding it to the FuncMap:

Full running example:

func main() {

    const text = "{{.Thingtype}} {{templname}}
"

    type Thing struct {
        Thingtype string
    }

    var thinglist = []*Thing{
        &Thing{"Old"},
        &Thing{"New"},
        &Thing{"Red"},
        &Thing{"Blue"},
    }

    t := template.New("things")

    templateName := func() string { return t.Name() }

    template.Must(t.Funcs(template.FuncMap{"templname": templateName}).Parse(text)) 

    for _, p := range thinglist {
        err := t.Execute(os.Stdout, p)
        if err != nil {
            fmt.Println("executing template:", err)
        }
    }
}

Outputs:

Old things
New things
Red things
Blue things

Playground link: http://play.golang.org/p/VAg5Gv5hCg