英文:
Get current template name?
问题
在Golang的text/html/template中,是否可以在不将其作为数据元素传递给模板的情况下访问当前模板的名称?
谢谢!
英文:
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!
答案1
得分: 3
我希望这是你的意思(来自http://golang.org/pkg/text/template/#Template.Name)
func (t *Template) Name() string
"Name返回模板的名称。"
如果你想从模板内部访问模板名称,我只能想到两种方法,一种是向template.FuncMap添加一个函数,另一种是像你建议的那样将名称添加为数据元素。
第一种方法可能看起来像这样:
var t = template.Must(template.New("page.html").ParseFiles("page.html"))
t.Funcs(template.FuncMap{"name": fmt.Sprint(t.Name())})
但是我无法在我快速尝试的时间内使其工作。希望它能帮助你找到正确的方向。
从长远来看,将名称作为数据元素添加可能更容易。
编辑:如果有人想知道如何使用template.FuncMap来实现它,基本上只需要在创建模板之后定义函数,然后将其添加到FuncMap中:
完整的运行示例:
func main() {
const text = "{{.Thingtype}} {{templname}}\n"
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)
}
}
}
输出:
Old things
New things
Red things
Blue things
Playground链接:http://play.golang.org/p/VAg5Gv5hCg
英文:
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}}\n"
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论