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

huangapple go评论101阅读模式
英文:

Golang: Multiple SQL query generate extra empty {{range.}}

问题

在应用程序中,我将为第二个查询使用完全不同的查询。第二个查询将是相当长的SELECT SIMILARITY查询。在这个问题中,我给出了一个简单的查询,以便更容易理解。

我需要在模板中从PostgreSQL打印数据。一切都正常工作,但输出的HTML中有额外的range

以下是HTML输出。你可以看到没有值的额外range

<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>

以下是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")
}

以下是模板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}}

我对模板中的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:

&lt;table&gt;
&lt;tr&gt;
&lt;th&gt;Title&lt;/th&gt;
&lt;th&gt;Content&lt;/th&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Nation&lt;/td&gt;
&lt;td&gt;Nation has various meanings, and the meaning has changed over time&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;/td&gt;
&lt;td&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;/table&gt;
&lt;h1&gt;ID number:&lt;/h1&gt;
&lt;h3&gt;&lt;/h3&gt;
&lt;h3&gt;5&lt;/h3&gt;

Below is server.go

package main
import (
&quot;database/sql&quot;
&quot;github.com/labstack/echo&quot;
_ &quot;github.com/lib/pq&quot;
&quot;html/template&quot;
&quot;io&quot;
&quot;log&quot;
&quot;net/http&quot;
)
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 &amp;echo.HTTPError{Error: err}
}
return nil
}
func main() {
e := echo.New()
db, err := sql.Open(&quot;postgres&quot;, &quot;user=postgres password=apassword dbname=lesson4 sslmode=disable&quot;)
if err != nil {
log.Fatal(err)
}
t := &amp;Template{
templates: template.Must(template.ParseFiles(&quot;public/views/testhere.html&quot;)),
}
e.Renderer(t)
e.Get(&quot;/post/:uritext&quot;, func(c *echo.Context) *echo.HTTPError {
rows, err := db.Query(&quot;SELECT title, content FROM gallery WHERE uri=$1&quot;, c.Param(&quot;uritext&quot;))
anotherquery, err := db.Query(&quot;SELECT id AS idnumber FROM gallery WHERE uri=$1&quot;, c.Param(&quot;uritext&quot;))
if err != nil {
log.Fatal(err)
}
gallery := []Gallery{}
for rows.Next() {
g := Gallery{}
err := rows.Scan(&amp;g.Title, &amp;g.Content)
if err != nil {
log.Fatal(err)
}
gallery = append(gallery, g)
}
for anotherquery.Next() {
g := Gallery{}
err := anotherquery.Scan(&amp;g.Idnumber)
if err != nil {
log.Fatal(err)
}
gallery = append(gallery, g)
}
return c.Render(http.StatusOK, &quot;onlytestingtpl&quot;, gallery)
})
e.Run(&quot;:4444&quot;)
}

Below is template public/views/testhere.html

{{define &quot;onlytestingtpl&quot;}}
&lt;table&gt;
&lt;tr&gt;
&lt;th&gt;Title&lt;/th&gt;
&lt;th&gt;Content&lt;/th&gt;
&lt;/tr&gt;
{{range.}}
&lt;tr&gt;
&lt;td&gt;{{.Title}}&lt;/td&gt;
&lt;td&gt;{{.Content}}&lt;/td&gt;
&lt;/tr&gt;
{{end}}
&lt;/table&gt;
&lt;h1&gt;ID number:&lt;/h1&gt;
{{range.}}
&lt;h3&gt;{{.Idnumber}}&lt;/h3&gt;
{{end}}
{{end}}

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

答案1

得分: 1

这是翻译好的内容:

我认为这是正确的。你运行了两个独立的查询:

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"))

然后从两个查询结果创建了一个切片:

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

所以你有两行数据:

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

这是你想要的吗?如果你想要合并它们,你可以修改查询语句为:

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

如果你想要两个独立的列表,也许你应该有两个独立的类型:

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

构建两个独立的列表,并在渲染时使用一个组合对象:

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

然后你的模板将会是:

{{range .Galleries}}
<tr>
<td>{{.Title}}</td>
<td>{{.Content}}</td>
</tr>
{{end}}
英文:

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

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

And then creating a slice from both:

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

So you have two rows:

{ &quot;Nation&quot;, &quot;Nation...&quot;, 0 }
{ &quot;&quot;, &quot;&quot;, 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, &quot;onlytestingtpl&quot;, Model{
Galleries: galleries,
IDNumbers: idnumbers,
})

And your template ends up with:

{{range .Galleries}}
&lt;tr&gt;
&lt;td&gt;{{.Title}}&lt;/td&gt;
&lt;td&gt;{{.Content}}&lt;/td&gt;
&lt;/tr&gt;
{{end}}

答案2

得分: 1

你的anotherquery没有扫描标题和内容:

err := anotherquery.Scan(&amp;g.Idnumber)

所以g的标题和内容被设置为空字符串。

英文:

You are not scanning title and content in your anotherquery:

err := anotherquery.Scan(&amp;g.Idnumber)

So the g's title and content are set to empty string.

huangapple
  • 本文由 发表于 2015年5月19日 23:23:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/30329793.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定