dongshen9058 2014-08-18 15:53
浏览 33

转到:使用模板在数组中显示数组

How do I insert a variable in a Go template like this - I have this code in HTML:

{{define "homepage"}}
<html>
<form action="/home/delete" method="POST">
    {{with .Posts}}
        {{range .}} 
            <p id="twt">{{ range $i := .Status}}{{$i}}<br><br></p>
            <button type="submit" id="xbutton" name="xdel" value="{{.Tweetid}}">Delete</button>
            {{end}}
        {{end}}
    {{end}}
</form>
</html>
{{end}}

The code in Go:

type User struct {
    Userid      int64
    Username    string
    Password    string
    Posts       []*Post
}

type Post struct {
    Tweetid     int
    Username    string
    Status      []string
}

func deletehandler(w http.ResponseWriter, r *http.Request) {
    currentuser = getUserName(r)
    postvalue = r.PostFormValue("xdel")
    DeleteTweet() 
    if currentuser != "" {
        as := Post{Username: currentuser, Status: ReadStatus(), Tweetid: ReadStatusId()}
        person := User{Username: currentuser, Posts: []*Post{&as}}
        t := template.Must(template.New("tele").ParseFiles("layout/home.html"))
            if err := t.ExecuteTemplate(w, "homepage", person); err != nil {
            panic(err)
        }
    } else {
    http.Redirect(w, r, "/", 302)
    }
}

//getting the .Tweetid
func ReadStatusId() (res int) {
    //some code to open and access the sql database
    rows, _ := db.Query("Select id from posts where tweet = ?", AddTweet)
    some code for error handling
    defer rows.Close()

    var status string
    for rows.Next() {
        err := rows.Scan(&status)
        if err != nil {
           fmt.Println(err)
        }
        fmt.Printf("this %s", status)
    }
    return
}

func main() {
    (//code for other handlers..)
    router.HandleFunc("/home/delete", deletehandler).Methods("POST")
}

However, the error message I get is

can't evaluate field Tweetid in type string

How do I fix this and allow .Tweetid to be read in the value string? If this helps I referred to this for the way I've used the templates: http://jan.newmarch.name/go/template/chapter-template.html

  • 写回答

1条回答 默认 最新

  • dqs13465424392 2014-08-18 17:58
    关注

    Try to change the template:

    {{range $p := .Posts}} 
       <p id="twt">{{ range $i := .Status}}{{$i}}<br><br></p>
       <button type="submit" id="xbutton" name="xdel" value="{{$p.Tweetid}}">Delete</button>
      {{end}}
    {{end}}
    

    using {{.Tweetid}} inside the {{ range $i := ... }} would reference {{$i.Tweetid}} adding range $p := .Posts}} and referencing it explicitly with {{$p.Tweetid}} will solve the problem

    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度