英文:
Go Programming - How to pass two structs in ExecuteTemplate
问题
我是一名Golang初学者,正在开发一个Web应用程序,以更好地理解Golang的概念。
我有一个HTML页面,我想在页面上显示有关用户和产品的一些信息。
所以,现在我只传递Product结构到Product的HTML模板中,像这样:
ExecuteTemplate(w, "product", Product)
但是我有一些信息不在这个结构体中,而是在User结构体中。
我想要做的是:
ExecuteTemplate(w, "product", Product, User)
我的意思是我想要将这两个结构体都传递给同一个模板。有办法可以做到这一点吗?
英文:
I am a golang beginner and I am developing a web application to understand better the golang concepts.
I have a html page which I want to show some informations about User and about a Product.
So, now I am passing only the Product struct to the Product html template, like this:
ExecuteTemplate(w, "product", Product)
But I have some informations that are not in this struct. That are in the User struct.
I would have to do something like this:
ExecuteTemplate(w, "product", Product, User)
I mean that I have to pass both structs to the same template. Is there a way to do this ?
答案1
得分: 4
将模板调用如下:
if err := t.ExecuteTemplate(w, "product",
struct{Product, User interface{}}{Product, User}); err != nil {
// 处理错误
}
在模板中,你可以通过以下方式访问 product
和 user
:
{{.Product}}
{{.User}}
英文:
Invoke the template as
if err := t.ExecuteTemplate(w, "product",
struct{Product, User interface{}}{Product, User}); err != nil {
// handle error
}
You can access product and user inside the template as:
{{.Product}}
{{.User}}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论