Golang中如何在HTML模板里遍历分片区块

Golang中如何在HTML模板里遍历分片区块 我需要帮助在HTML页面中对数组和切片进行范围遍历。当我尝试对数组和块进行范围遍历时,它们没有显示在HTML页面上,但页眉部分成功传递到了HTML页面。

如果这是一个新手问题,请见谅。非常感谢您的帮助。

package main

import (

    "fmt"

    "html/template"

    "log"

    "math/rand"

    "net/http"

    "strconv"

    "time"

    //entities "deadmeat.pro/chunker/src/entities"

    //helpers "deadmeat.pro/chunker/src/helpers"

)

///这是页眉页脚结构体。当传递给模板时,它工作正常
type HeaderFooter struct {

    Header, Footer string

}

///这是Chunks结构体,用于包含切片后的块和随机化的用户,以便分配给切片块。
///这在HTML表单中没有显示。
type Chunks struct {

    SliceChunks  [][]string

    SliceRandoms []string

    ChunkId      []int

}

   //包含要传递到模板文件中的Chunks结构体和HeaderFooter结构体的数据
   type Data struct{
	Chunk Chunks
	HF    HeaderFooter
    }

//此函数将传入的数组列表分块,分成与用户数量相等的块。
func SliceChunker(items []string, n int) [][]string {

    if n < 0 {

        return nil

    }

    chunks := make([][]string, n)

    for i := range chunks {

        m := (len(items) + (n - 1)) / n

        chunks[i] = items[:m:m]

        items = items[m:]

        n--

        fmt.Printf("CHUNK %2d = %d : %v\n", i, m, chunks[i])

    }

    return chunks

}


///此函数随机化用户,以便块的分配不是预先确定的,而是随机的
func SliceRand(sliceItems []string) []string {

    rand.Seed(time.Now().UnixNano())

    rand.Shuffle(len(sliceItems), func(i, j int) { sliceItems[i], sliceItems[j] = sliceItems[j], sliceItems[i] })

    return sliceItems

}

//将数据传递到HTML模板页面的Index页面方法
func (d Data) Index(w http.ResponseWriter, r *http.Request) {

var tpl *template.Template
tpl = template.Must(template.ParseGlob("form/*.html"))
//template.Must(tpl.ParseGlob("form/register/*.html"))

var sliceItems []string
users := []string{"Hosea", "Clarence Obando", "Mukhongo Simiyu", "Jimmie Carter", "Qabale", "McDonald", "Sierra", "Tyra", "James",
	"Kimberly", "Waweru", "Stata", "Karis", "Brigg Symons", "Abdi", "Kuti", "Eliud", "Wolde", "Buno", "Cheptoo Kipsang"}

A2Z := []string{"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V",
	"W", "X", "Y", "Z"}

for x := 0; x <= 9; x++ {
	for _, i := range A2Z {
		sliceItems = append(sliceItems, strconv.Itoa(x)+i)
	}
}
fmt.Println("--------------------------------------------------------------------------")

d.Chunk.SliceRandoms = helpers.SliceRand(users)
d.Chunk.SliceChunks = helpers.SliceChunker(sliceItems, len(users))
d.HF.Header = "Ukirusha mawe kwa mbwa wengi, atakaye piga nduru ndiye aliye gongwa : The guilty ones are always.."
d.HF.Footer = "He that sleepeth with an itchy ■■■■ wakes up with a smelly finger"
for i := range d.Chunk.SliceChunks {
	d.Chunk.ChunkId = append(d.Chunk.ChunkId, i+1)
}

tpl.ExecuteTemplate(w, "index.html", d)
fmt.Println(d)
d = Data{}
fmt.Println("END --->>>>>> = ", d)
func main() {

    log.Println("Server started on: http://localhost:8080")

    http.HandleFunc("/", Index)

    if err := http.ListenAndServe(":8080", nil); err != nil {

        log.Fatal(err)

    }

}

位于名为form的文件夹中的HTML部分如下所示:

    <!DOCTYPE html>

    <html lang="en">

    <head>

        <meta charset="UTF-8">

        <meta name="viewport" content="width=device-width, initial-scale=1.0">

        <title>Document</title>

    </head>

    <body>

        {{.HF.Header}}<br>

        <table border="1">

            <thead>

                <tr>

                    <td>ID</td>

                    <td>USER</td>

                    <td>ITEMS</td>

                </tr>

            </thead>

            <tbody>

                {{ range .Chunk }}

                <tr>

                    <td> {{ .ChunkId }} </td>

                    <td>{{ .SliceRandoms }}</td>

                    <td> {{ .SliceChunks }} </td>

                </tr>

                {{ end }}

            </tbody>

        </table>

        <h1>{{.HF.Footer}}</h1><br>

    </body>

    </html>

块切片和用户切片似乎无法传递到Index页面。传递后,它们没有显示在索引表单上。

页脚和页眉数据显示正常,但切片似乎无法传递。


更多关于Golang中如何在HTML模板里遍历分片区块的实战教程也可以访问 https://www.itying.com/category-94-b0.html

6 回复

我已经尝试过这个方法了,但问题依然存在。

更多关于Golang中如何在HTML模板里遍历分片区块的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html


尝试将 chunk 改为大写:Chunk

也许展示一下你实际的代码。

请通过以下方式帮助我们帮助你:

  • 发布一个能重现问题的最小示例
  • 使用编辑窗口顶部的 < /> 按钮将你的代码包裹在代码块中。

当我尝试使用一个HTML列表项时,

{{ range .Chunk.SliceChunks}}

    <li>{{.}}</li>

    {{ end }}

它是有效的,但如果我这样做

{{ range .Chunk}}

    <li>{{.SliceChunks}}</li>

    {{ end }}

它就不再工作了。我可能哪里出错了?

经过长时间的尝试,在表格的<td>中使用<li>元素虽然得到了我想要的结果,但我还是想知道如何能轻松地做到这一点,而不必在<td>中使用<li>。因为在某些情况下,当数据块非常长时,它们会重叠,但其他列表项没有意识到这一点,导致数据表示不匹配。

我还想知道如何从分块切片中移除 [] 符号。

<body>

    {{.HF.Header}}<br>
    <h1>{{.HF.Footer}}</h1>

    <table>
        <thead>
            <tr>
                <td>ID</td>
                <td>USERS</td>
                <td>ITEMS</td>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td>
                    {{ range .Chunk.ChunkId}}
                    <li style="list-style-type:none">{{.}}</li>
                    {{ end }}
                </td>
                <td>
                    {{ range .Chunk.SliceRandoms}}
                    <li style="list-style-type:none">{{.}}</li>
                    {{ end }}
                </td>
                <td>
                    {{ range .Chunk.SliceChunks}}
                    <li style="list-style-type:none">{{.}}</li>
                    {{ end }}
                </td>
            </tr>
        </tbody>
    </table>
    <h1>{{.HF.Footer}}</h1><br>
</body>

在HTML模板中遍历切片时,需要正确访问嵌套结构体的字段。你的模板中{{ range .Chunk }}试图遍历Chunk结构体本身,而不是其中的切片字段。以下是修正后的模板代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    {{.HF.Header}}<br>
    <table border="1">
        <thead>
            <tr>
                <td>ID</td>
                <td>USER</td>
                <td>ITEMS</td>
            </tr>
        </thead>
        <tbody>
            {{ range $index, $chunk := .Chunk.SliceChunks }}
            <tr>
                <td>{{ index $.Chunk.ChunkId $index }}</td>
                <td>{{ index $.Chunk.SliceRandoms $index }}</td>
                <td>
                    {{ range $item := $chunk }}
                        {{ $item }}
                    {{ end }}
                </td>
            </tr>
            {{ end }}
        </tbody>
    </table>
    <h1>{{.HF.Footer}}</h1><br>
</body>
</html>

或者使用索引变量来访问对应的切片元素:

<tbody>
    {{ range $index := .Chunk.ChunkId }}
    <tr>
        <td>{{ $index }}</td>
        <td>{{ index $.Chunk.SliceRandoms (sub $index 1) }}</td>
        <td>
            {{ range $item := index $.Chunk.SliceChunks (sub $index 1) }}
                {{ $item }}
            {{ end }}
        </td>
    </tr>
    {{ end }}
</tbody>

如果需要使用sub函数,需要在模板中注册自定义函数:

func (d Data) Index(w http.ResponseWriter, r *http.Request) {
    tpl := template.Must(template.New("").Funcs(template.FuncMap{
        "sub": func(a, b int) int { return a - b },
    }).ParseGlob("form/*.html"))
    
    // ... 其余代码保持不变
}

确保你的Data结构体正确初始化并传递了所有切片数据。在模板中,使用$.Chunk.SliceChunks来访问嵌套结构体中的切片字段,然后通过索引访问对应的元素。

回到顶部