【问题标题】:How to print the specific in an HTML file using golang?如何使用 golang 打印 HTML 文件中的特定内容?
【发布时间】:2021-12-24 14:01:06
【问题描述】:

在这段代码中,我想在 HTML 文件中使用并给出一个特定的细节,比如标题或价格。

问题在于,有多个标题和价格,当我打印特定的标题和价格时,它会成功打印特定的数据,但我不知道如何在 HTML 文件中使用它来打印特定的数据。我所知道的关于 GOHTML 的只有 {{.Heading}},但它不起作用。有没有其他办法?

package main

import "net/http"

type Details struct {
    Heading string
    Price   string
}

var Detail = []Details{
    {
        Heading: "First Cloth",
        Price:   "$59",
    },
    {
        Heading: "Second Cloth",
        Price:   "$49",
    },
}

func Main(w http.ResponseWriter, r *http.Request) {
    HomeTmpl.Execute(w, Detail)
    // fmt.Println(Detail[1].Heading) // For specific data
}

【问题讨论】:

    标签: html go templates go-templates


    【解决方案1】:

    您可以使用内置的index 模板函数从切片中获取元素:

    {{ (index . 1).Heading }}
    

    测试它:

    t := template.Must(template.New("").Parse(`{{ (index . 1).Heading }}`))
    if err := t.Execute(os.Stdout, Detail); err != nil {
        panic(err)
    }
    

    哪些输出(在Go Playground 上试试):

    Second Cloth
    

    【讨论】:

    • 我执行了模板并将 {{ (index . 1).Heading }} 放入 HTML 文件中,但它打印了整个 HTML 代码。虽然我试图在浏览器中显示它。
    • 您的模板是否呈现完整的 HTML 文档?它是否以<html> 开头?还要检查Template.Execute()返回的错误。
    • 成功了。我将os.Stdout 更改为w 并将其呈现在HTML 文件中。谢谢icza!
    • @SumbaloDi 是的,os.Stdout 只是为了测试/证明它有效。在 HTTP 处理程序中,您必须使用 w 来写入 HTTP 响应。
    猜你喜欢
    • 2021-05-21
    • 2011-12-02
    • 1970-01-01
    • 2020-04-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多