dsdtumf776629385 2014-08-14 13:21
浏览 188
已采纳

GO:使用html / template提供模板时出错

I'm using html/template to serve html but I'm not sure if I'm using it correctly. I've only pasted the relevant code below (not complete):

This is my Go code:

func homehandler(w http.ResponseWriter, r *http.Request) {
    userName := getUserName(r) //this is defined somewhere
    if userName != "" {
        t := template.Must(template.New("Tele").Parse(homePage))
    t.Execute(w, ReadData()) //ReadData() is a function that reads from the MySQL database and returns a string array
    } else {
        (...some code)
    }
}

func ReadData() ([]string) {
    db, _ := sql.Open("mysql", "user1@/my_db")
    (...some code)    

    rows, err := db.Query("select tweet from posts where username = ?", AddUser.Name) //AddUser is defined somewhere
    (...some code)

    for rows.Next() {
        err := rows.Scan(&tweet)
        if err != nil {
            fmt.Println(err)
        }
    v := append(tweetarray, tweet)
    fmt.Println(v)
    return v
    }
    return []string{}
}

The html portion in the Go code:

const homePage = `
<html>
<h1>hi {{ .userName}}</h1>
<form action="/home/tweets" method="POST">
<label for="name">Tweet</label>
<input type="text" id="tweet" name="twt"</input>
<button type="Tweet">Tweet</button>
<h2>{{range $i := .tweetarray}} {{ $i }} {{end}}</h2>
`

The HTML doesn't appear at all. What am I doing wrong in the code?

  • 写回答

1条回答 默认 最新

  • duanbixia7738 2014-08-14 14:08
    关注

    Check your errors! (sorry for the bold, but this is the answer to so many Go questions)

    t.Execute() returns an error because you have malformed html in your template.

    html/template:Tele: "<" in attribute name: "</input>
    <button type=\"Tweet\">Tw"
    

    When troubleshooting something like this, try running each of the parts in isolation, or at least log some debugging information to go with it.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 求螺旋焊缝的图像处理
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面