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.

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

报告相同问题?

悬赏问题

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