繁体   English   中英

用tabwriter去文本/模板

[英]go text/template with tabwriter

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

如何在文本/ 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()

此外,将标签添加到您希望列中断的模板。

操场的例子

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM