【问题标题】:can't evaluate field data in type string无法评估字符串类型的字段数据
【发布时间】:2020-03-22 18:34:29
【问题描述】:

尝试将变量数据的内容打印到 html 页面中:

package main

import (
    "net/http"
    "fmt"
    "log"
    "html/template"
)

var tpl *template.Template

func init(){
    tpl= template.Must(template.ParseGlob("*.html"))
}

func main(){
    http.HandleFunc("/",  index)
    http.HandleFunc("/process", processor)
    http.ListenAndServe(":8080", nil)
}

func index(w http.ResponseWriter, r *http.Request){
    tpl.ExecuteTemplate(w, "index.html",nil)
}

func processor(w http.ResponseWriter, r *http.Request){
    if r.Method != "GET" {
        http.Redirect(w,r,"/", http.StatusSeeOther)
        return
    }
    data := r.FormValue("data")
    fmt.Printf("%s",data)
    err:=tpl.ExecuteTemplate(w, "processor.html", string(data))
    if err != nil {
    log.Fatalf("execution failed: %s", err)
}
    //tpl.ExecuteTemplate(w, "processor.html",data)
}

这是html

<html>
    <head>
        <title>PROCESSOR</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
    </head>
    <body>
        <h1>{{.data}}</h1>
    </body>
</html>

这是我的 shell 打印出来的:

poo2020/03/22 19:13:50 execution failed: template: processor.html:8:11: executing "processor.html" at <.data>: can't evaluate field data in type string
exit status 1

便便是数据的内容(证明我从初始 html 页面正确获取它。 检查了一些类似的问题,尝试使用变量 $data,但我遇到了同样的问题。

【问题讨论】:

    标签: html templates go


    【解决方案1】:

    你将一个字符串变量传递给模板处理器,所以这就是它的上下文中的全部内容,所以你必须使用:

    {{.}}
    

    在模板中打印它。或者,您可以将带有“数据”字段的上下文传递为:

     err:=tpl.ExecuteTemplate(w, "processor.html", map[string]interface{}{"data":string(data)})
    

    并使用

    {{.data}}
    

    在模板中。

    您传递给ExecuteTemplate 的任何对象都可以使用{{.}} 访问。符号 {{.data}} 将访问该对象中的字段名称 data

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-06-08
      • 2022-08-16
      • 1970-01-01
      • 2020-11-09
      • 2017-03-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多