使用tabwriter的go text/template

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

go text/template with tabwriter

问题

我尝试使用text/template创建一个漂亮的表格,但是列没有对齐。text/tabwriter可以工作,但是text/template可以使代码更整洁。

我该如何在text/template中使用text/tabwriter?

这是我的测试代码:

package main

import (
	"os"
	"text/template"
)

type a struct {
	Title string
	Items []items
}

type items struct {
	Title string
	Body  string
}

const templ = `{{.Title}}{{range .Items}}
{{.Title}}	{{.Body}}{{end}}
`

func main() {
	data := a{
		Title: "title1",
		Items: []items{
			{"item1", "body1"},
			{"item2", "body2"},
			{"verylongitem3", "body3"}},
	}
	t := template.New("test")
	t, _ = t.Parse(templ)
	t.Execute(os.Stdout, data)
}

输出结果:

title1
item1	body1
item2	body2
verylongitem3	body3

希望对你有帮助!

英文:

I try to have a pretty table with text/template but the columns are not aligned.
text/tabwriter work but text/template make a cleaner code.

How can I use text/template with text/tabwriter?

This is my test :

package main

import (
	"os"
	"text/template"
)

type a struct {
	Title string
	Items []items
}

type items struct {
	Title string
	Body  string
}

const templ = `{{.Title}}{{range .Items}}
{{.Title}}	{{.Body}}{{end}}
`

func main() {
	data := a{
		Title: "title1",
		Items: []items{
			{"item1", "body1"},
			{"item2", "body2"},
			{"verylongitem3", "body3"}},
	}
	t := template.New("test")
	t, _ = t.Parse(templ)
	t.Execute(os.Stdout, data)
}

Output :

title1
item1	body1
item2	body2
verylongitem3	body3

答案1

得分: 8

t.Execute(os.Stdout, data)

替换为

w := tabwriter.NewWriter(os.Stdout, 8, 8, 8, ' ', 0)
if err := t.Execute(w, data); err != nil {
	// 处理错误
}
w.Flush()

此外,在模板中添加制表符,以在需要的地方进行列分隔。

playground 示例

英文:

Replace

t.Execute(os.Stdout, data)

with

w := tabwriter.NewWriter(os.Stdout, 8, 8, 8, ' ', 0)
if err := t.Execute(w, data); err != nil {
	// handle error
}
w.Flush()

Also, add tabs to the template where you want the column breaks.

playground example

huangapple
  • 本文由 发表于 2016年4月17日 22:07:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/36677578.html
匿名

发表评论

匿名网友

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

确定