在Go语言的html/template中循环遍历数组元素。

huangapple go评论88阅读模式
英文:

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 &lt;br&gt;).

My code consists of the following 3 files.

The main.go file:

package main
import (
&quot;bytes&quot;
&quot;encoding/json&quot;
&quot;fmt&quot;
&quot;html/template&quot;
&quot;io/ioutil&quot;
&quot;net/http&quot;
&quot;github.com/dimchansky/utfbom&quot; //used for removing BOM from utf-8
)
//import struct
type dataStruct struct {
GroupName    string   `json:&quot;name&quot;`
GroupMembers []string `json:&quot;Members&quot;`
}
type Request struct {
}
//File path
const jsonImport = &quot;./static/JSONFiles/OUdata.json&quot;
func main() {
http.HandleFunc(&quot;/&quot;, pageHandler)
http.ListenAndServe(&quot;:2323&quot;, 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, &amp;theData)
if err != nil {
fmt.Println(&quot;error!!&quot;, err)
}
//loop through and print JSON in terminal
for i := 0; i &lt; len(theData); i++ {
fmt.Println(theData[i].GroupName)
for j := 0; j &lt; 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(&quot;rolegrouppage.html&quot;)
t.Execute(w, p)
}

The html template file (rolegrouppage.html):

&lt;!DOCTYPE html&gt;
&lt;html lang=&quot;en&quot;&gt;
&lt;head&gt;
&lt;meta charset=&quot;UTF-8&quot;&gt;
&lt;title&gt;Hiya Buddy!&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;
{{range .}}
&lt;h1&gt;
{{.GroupName}}
&lt;/h1&gt;
&lt;h4&gt;
{{.GroupMembers}}
&lt;/h4&gt; 
{{end}}
&lt;/body&gt;
&lt;/html&gt;

And the data file (OUdata.json):

[
{
&quot;name&quot;:  &quot;Group 1&quot;,
&quot;Members&quot;:  [
&quot;Mrs Smith&quot;,
&quot;Ms Sigmundsdottir&quot;,
&quot;Mr Arnason&quot;
]
},
{
&quot;name&quot;:  &quot;Group 2&quot;,
&quot;Members&quot;:  [
&quot;Mrs Gunnarsdottir&quot;,
&quot;Mr Bjarnason&quot;,
&quot;Ms Sturlud&#243;ttir&quot;,
&quot;Mrs Gr&#237;msd&#243;ttir&quot;,
&quot;Mr Rafnkelsson&quot;
]
}
]

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一样。

&lt;body&gt;
{{ range . }}
  &lt;h1&gt;{{ .GroupName }}&lt;/h1&gt;
  {{ range .GroupMembers }}
  &lt;h4&gt;{{ . }}&lt;/h4&gt;
  {{ end }}
{{ end }}
&lt;/body&gt;
英文:

You need to range over the GroupMembers field, just like you are ranging over the theData value.

&lt;body&gt;
{{ range . }}
  &lt;h1&gt;{{ .GroupName }}&lt;/h1&gt;
  {{ range .GroupMembers }}
  &lt;h4&gt;{{ . }}&lt;/h4&gt;
  {{ end }}
{{ end }}
&lt;/body&gt;

huangapple
  • 本文由 发表于 2021年9月24日 12:34:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/69309606.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定