douhe1002 2015-05-19 15:23
浏览 24
已采纳

Golang:多个SQL查询会产生额外的空{{range。}}

In the application, I will use totally different query for the second query. The second query will be quite long SELECT SIMILARITY query. In this question, I give simple query to make it easier to understand

I need to print data from PostgreSQL in template. Everything works fine but output HTML has extra range.

Below is the HTML output. You can see the extra range that have no value:

<table>
    <tr>
        <th>Title</th>
        <th>Content</th>
    </tr>

    <tr>
        <td>Nation</td>
        <td>Nation has various meanings, and the meaning has changed over time</td>
    </tr>

    <tr>
        <td></td>
        <td></td>
    </tr>

</table>

<h1>ID number:</h1>

<h3></h3>

<h3>5</h3>

Below is server.go

package main

import (
    "database/sql"
    "github.com/labstack/echo"
    _ "github.com/lib/pq"
    "html/template"
    "io"
    "log"
    "net/http"
)

type Gallery struct {
    Title, Content, Idnumber string
}

type (
    Template struct {
        templates *template.Template
    }
)

func (t *Template) Render(w io.Writer, name string, data interface{}) *echo.HTTPError {
    if err := t.templates.ExecuteTemplate(w, name, data); err != nil {
        return &echo.HTTPError{Error: err}
    }
    return nil
}

func main() {
    e := echo.New()

    db, err := sql.Open("postgres", "user=postgres password=apassword dbname=lesson4 sslmode=disable")
    if err != nil {
        log.Fatal(err)
    }

    t := &Template{
        templates: template.Must(template.ParseFiles("public/views/testhere.html")),
    }
    e.Renderer(t)

    e.Get("/post/:uritext", func(c *echo.Context) *echo.HTTPError {

        rows, err := db.Query("SELECT title, content FROM gallery WHERE uri=$1", c.Param("uritext"))
        anotherquery, err := db.Query("SELECT id AS idnumber FROM gallery WHERE uri=$1", c.Param("uritext"))
        if err != nil {
            log.Fatal(err)
        }

        gallery := []Gallery{}

        for rows.Next() {
            g := Gallery{}
            err := rows.Scan(&g.Title, &g.Content)

            if err != nil {
                log.Fatal(err)
            }

            gallery = append(gallery, g)
        }

        for anotherquery.Next() {
            g := Gallery{}
            err := anotherquery.Scan(&g.Idnumber)

            if err != nil {
                log.Fatal(err)
            }

            gallery = append(gallery, g)
        }

        return c.Render(http.StatusOK, "onlytestingtpl", gallery)
    })

    e.Run(":4444")
}

Below is template public/views/testhere.html

{{define "onlytestingtpl"}}
<table>
    <tr>
        <th>Title</th>
        <th>Content</th>
    </tr>
    {{range.}}
    <tr>
        <td>{{.Title}}</td>
        <td>{{.Content}}</td>
    </tr>
    {{end}}
</table>

<h1>ID number:</h1>
{{range.}}
<h3>{{.Idnumber}}</h3>
{{end}}

{{end}}

I have feeling about the range in template but I have no idea since no error.

  • 写回答

2条回答 默认 最新

  • dongzhouji4021 2015-05-19 17:00
    关注

    It looks right to me. You are running two separate queries:

    rows, err := db.Query("SELECT title, content FROM gallery WHERE uri=$1", c.Param("uritext"))
    anotherquery, err := db.Query("SELECT id AS idnumber FROM gallery WHERE uri=$1", c.Param("uritext"))
    

    And then creating a slice from both:

    gallery = append(gallery, g)
    gallery = append(gallery, g)
    

    So you have two rows:

    { "Nation", "Nation...", 0 }
    { "", "", 5 }
    

    Is that what you wanted? If you want them merged you can just change your query to:

    SELECT title, content, id as idnumber FROM gallery WHERE uri=$1
    

    If you wanted two separate lists then maybe you should have two separate types:

    type Gallery struct {
        Title, Content string
    }
    type IDNumber string
    

    Build two separate lists and use a combined object for your render:

    type Model struct {
        Galleries []Gallery
        IDNumbers []IDNumber
    }
    return c.Render(http.StatusOK, "onlytestingtpl", Model{
        Galleries: galleries,
        IDNumbers: idnumbers,
    })
    

    And your template ends up with:

    {{range .Galleries}}
    <tr>
        <td>{{.Title}}</td>
        <td>{{.Content}}</td>
    </tr>
    {{end}}
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 请问如何在openpcdet上对KITTI数据集的测试集进行结果评估?
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗
  • ¥15 ikuai客户端l2tp协议链接报终止15信号和无法将p.p.p6转换为我的l2tp线路
  • ¥15 phython读取excel表格报错 ^7个 SyntaxError: invalid syntax 语句报错