使用 tabwriter 转到文本/模板

标签 go

我尝试制作一个带有文本/模板的漂亮表格,但列没有对齐。 text/tabwriter 工作,但 text/template 使代码更清晰。

如何将文本/模板与文本/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

最佳答案

替换

t.Execute(os.Stdout, data)

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

此外,将制表符添加到模板中您想要分栏符的位置。

playground example

关于使用 tabwriter 转到文本/模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36677578/

相关文章:

go - 如何在 Goreleaser 中为每个目标设置 `-ldflags` 值?

go - sqlx 返回空结构,即使它存在

go - 使用 errgroup 在第一个错误时取消 goroutine

go - 获取错误 : all goroutines are asleep - deadlock

golang google-bigquery v2 api指定目的表

sockets - 多个 http.Requests 给出 "can' t 分配请求的地址,“除非加速

go - RPC调用找不到方法

datetime - 无法在 Golang 的时间包中遍历年底之后的日子

go - golang获取kubernetes资源(30000+ configmaps)失败

go - 尽管 GO AWS SDK 没有错误,但无法使 CloudWatchLogs 正常工作