英文:
Looping through array elements in GoLang in the html/template
问题
我有一个Go Web服务器,我想在其中显示一个JSON文件的内容。
main.go文件读取文件并将数据放入一个结构体中。当我直接循环遍历结构体中的数据时,我可以像这样在终端中打印数据:
Group 1
Member1
Member2
Member3
Group2
Member1
Member2
Member3
这正是我想要在HTML中显示的内容,以便我可以对其进行样式设置。
当我将数据发送到模板时,我得到以下结果:
Group1
[Member1 Member2 Member3]
Group2
[Member1 Member2 Member3]
在我看来,GroupMembers以一个字符串的形式出现。我想知道如何让模板将它们作为单独的元素读取,以便我可以添加HTML(例如<br>
)。
我的代码包括以下3个文件。
main.go文件:
package main
import (
"bytes"
"encoding/json"
"fmt"
"html/template"
"io/ioutil"
"net/http"
"github.com/dimchansky/utfbom" //用于删除UTF-8中的BOM
)
//导入结构体
type dataStruct struct {
GroupName string `json:"name"`
GroupMembers []string `json:"Members"`
}
type Request struct {
}
//文件路径
const jsonImport = "./static/JSONFiles/OUdata.json"
func main() {
http.HandleFunc("/", pageHandler)
http.ListenAndServe(":2323", nil)
}
func pageHandler(w http.ResponseWriter, r *http.Request) {
//读取文件
theJson, err := ioutil.ReadFile(jsonImport)
if err != nil {
fmt.Print(err)
}
//去除BOM
data, err := ioutil.ReadAll(utfbom.SkipOnly(bytes.NewReader(theJson)))
if err != nil {
fmt.Println(err)
return
}
//创建一个新的结构体
var theData []dataStruct
//将JSON放入结构体中
err = json.Unmarshal(data, &theData)
if err != nil {
fmt.Println("error!!", err)
}
//循环遍历并在终端中打印JSON
for i := 0; i < len(theData); i++ {
fmt.Println(theData[i].GroupName)
for j := 0; j < len(theData[i].GroupMembers); j++ {
fmt.Println(theData[i].GroupMembers[j])
}
}
//在终端中打印一个GroupMember的测试
fmt.Println(theData[0].GroupMembers[1])
p := theData
t, _ := template.ParseFiles("rolegrouppage.html")
t.Execute(w, p)
}
HTML模板文件(rolegrouppage.html):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Hiya Buddy!</title>
</head>
<body>
{{range .}}
<h1>
{{.GroupName}}
</h1>
<h4>
{{.GroupMembers}}
</h4>
{{end}}
</body>
</html>
数据文件(OUdata.json):
[
{
"name": "Group 1",
"Members": [
"Mrs Smith",
"Ms Sigmundsdottir",
"Mr Arnason"
]
},
{
"name": "Group 2",
"Members": [
"Mrs Gunnarsdottir",
"Mr Bjarnason",
"Ms Sturludóttir",
"Mrs Grímsdóttir",
"Mr Rafnkelsson"
]
}
]
实现这个的最佳方法是重新格式化JSON文件并以不同的方式循环遍历它吗?还是有一种方法可以从html/template中访问每个"元素"?
英文:
I have a Go web server where I would like to display the contents of a JSON file..
The main.go reads the file and puts the data into a struct. When I loop through the data in the struct directly, I can print the data in the terminal like this:
Group 1
Member1
Member2
Member3
Group2
Member1
Member2
Member3
Which is what I want in my html so that I can style it.
When I send the data to the template, I get the following
Group1
[Member1 Member2 Member3]
Group2
[Member1 Member2 Member3]
It looks to me like the GroupMembers are coming in as one string. I would like to know how I can get the template to read them as individual elements so that I can add html (e.g. a <br>
).
My code consists of the following 3 files.
The main.go file:
package main
import (
"bytes"
"encoding/json"
"fmt"
"html/template"
"io/ioutil"
"net/http"
"github.com/dimchansky/utfbom" //used for removing BOM from utf-8
)
//import struct
type dataStruct struct {
GroupName string `json:"name"`
GroupMembers []string `json:"Members"`
}
type Request struct {
}
//File path
const jsonImport = "./static/JSONFiles/OUdata.json"
func main() {
http.HandleFunc("/", pageHandler)
http.ListenAndServe(":2323", nil)
}
func pageHandler(w http.ResponseWriter, r *http.Request) {
//read file
theJson, err := ioutil.ReadFile(jsonImport)
if err != nil {
fmt.Print(err)
}
//get rid of BOM
data, err := ioutil.ReadAll(utfbom.SkipOnly(bytes.NewReader(theJson)))
if err != nil {
fmt.Println(err)
return
}
//make a new struct
var theData []dataStruct
//put the JSON into a struct
err = json.Unmarshal(data, &theData)
if err != nil {
fmt.Println("error!!", err)
}
//loop through and print JSON in terminal
for i := 0; i < len(theData); i++ {
fmt.Println(theData[i].GroupName)
for j := 0; j < len(theData[i].GroupMembers); j++ {
fmt.Println(theData[i].GroupMembers[j])
}
}
//Print test of 1 GroupMember in terminal
fmt.Println(theData[0].GroupMembers[1])
p := theData
t, _ := template.ParseFiles("rolegrouppage.html")
t.Execute(w, p)
}
The html template file (rolegrouppage.html):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Hiya Buddy!</title>
</head>
<body>
{{range .}}
<h1>
{{.GroupName}}
</h1>
<h4>
{{.GroupMembers}}
</h4>
{{end}}
</body>
</html>
And the data file (OUdata.json):
[
{
"name": "Group 1",
"Members": [
"Mrs Smith",
"Ms Sigmundsdottir",
"Mr Arnason"
]
},
{
"name": "Group 2",
"Members": [
"Mrs Gunnarsdottir",
"Mr Bjarnason",
"Ms Sturludóttir",
"Mrs Grímsdóttir",
"Mr Rafnkelsson"
]
}
]
Would the best way to achieve this be to reformat the JSON file and somehow loop through it differently? Or is there a way to access each "element" from the html/template?
答案1
得分: 1
你需要在GroupMembers
字段上使用range
,就像你在theData
值上使用range
一样。
<body>
{{ range . }}
<h1>{{ .GroupName }}</h1>
{{ range .GroupMembers }}
<h4>{{ . }}</h4>
{{ end }}
{{ end }}
</body>
英文:
You need to range
over the GroupMembers
field, just like you are ranging over the theData
value.
<body>
{{ range . }}
<h1>{{ .GroupName }}</h1>
{{ range .GroupMembers }}
<h4>{{ . }}</h4>
{{ end }}
{{ end }}
</body>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论