douliaopan1419 2016-04-17 14:07
浏览 8
已采纳

与制表师一起去文本/模板

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条回答 默认 最新

  • duangua6912 2016-04-17 14:14
    关注

    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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大