英文:
Multiple forms from database in a single Golang web template
问题
我正在使用Golang进行我的第一个项目,并尝试创建一个包含两个列表的表单,以供选择选项,如下所示:
然而,如果我想让这些列表从SQLite数据库的两个表中检索条目,模块"templates"只允许我在一个模板中发送一个查询,类似于:
func Person(w http.ResponseWriter, r *http.Request) {
db := ConnectDB()
arrP := GetPerson(db)
templates.ExecuteTemplate(w, "person", arrP)
}
因此,只有第一个列表将从范围中提取信息(在这种特殊情况下,它将显示来自"person"表的有效选项),而第二个列表将继续显示我自己硬编码的条目。
感谢@Zombo的回复。为了澄清一些事情,我发布的函数打开与数据库的连接
db := ConnectDB()
然后它创建arrP('person'类型的数组)并调用内置的templates.ExecuteTemplate()
templates.ExecuteTemplate(w, "person", arrP)
它将呈现"person"的HTML模板。然而,在同一页中,我尝试放置另一个选择表单来选择"Service"。如果我尝试像这样做
func Person(w http.ResponseWriter, r *http.Request) {
db := ConnectDB()
arrP := GetPerson(db)
arrS := GetService(db)
templates.ExecuteTemplate(w, "person", arrP, arrS)
}
它会报错,因为我传递了比预期更多的参数。因此,只有人员列表会正确地从数据库中渲染出信息;然而,服务列表没有任何来源来提取其条目。
英文:
I'm doing my first project in Golang, and I'm trying to create a form with two lists to choose options from, as following:
webpage with a form, it has two lists to choose options from and a text field
However, If I want to make those lists to retrieve their entries from two tables from a SQLite database, the module "templates" only allows me to send one query per template, something like
func Person(w http.ResponseWriter, r *http.Request) {
db := ConnectDB()
arrP := GetPerson(db)
templates.ExecuteTemplate(w, "person", arrP)
}
Thus, only the first list will pull up information from the range (in this particular case, it'll display valid options from the 'person' table, and the second list will keep showing the entries I hard coded myself.
Thanks @Zombo for replying. To clarify some things, the function I posted opens up the connection with the database
db := ConnectDB()
Then it creates arrP (array of 'person' type) and calls the built-in templates.ExecuteTemplate()
templates.ExecuteTemplate(w, "person", arrP)
Which will render the "person" html template. However, in that same page I'm trying to put another selection form to choose 'Service'. If I try something like
func Person(w http.ResponseWriter, r *http.Request) {
db := ConnectDB()
arrP := GetPerson(db)
arrS := GetService(db)
templates.ExecuteTemplate(w, "person", arrP, arrS)
}
It will complain because I'm passing more arguments than expected. Therefore, only the list of persons will render properly with the information from the database; however, the list of services doesn't have any source to pull its entries from.
答案1
得分: 1
@Zombo给出了一个简洁的答案,使用map我们可以将多个数组传递给模板,以渲染多个列表/表格。
map[string]any{"arrP": arrP, "arrS": arrS}
然后在.tmpl文件中使用*$.arrS*。
英文:
@Zombo gave a neat answer, using a map we can pass multiple arrays to a template to render several list / tables.
map[string]any{“arrP”: arrP, “arrS”: arrS}
And then use $.arrS in the .tmpl file.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论