charmbracelet/glamour

How to print a formatted table?

crdpa opened this issue · 1 comments

crdpa commented

My table string is like this:

| Artist | Song | Album | Plays |
---
| Pure Wrath | Years of Silence | Hymn to the Woeful Hearts | 1 |
| Dio | When a Woman Cries | Dream Evil | 1 |
| Intestine Baalism | Tyrant | An Anatomy of the Beast | 1 |
| Amorphis | The Wolf | Halo | 1 |
| Amorphis | The Moon | Halo | 1 |

But the output is just formatting the headers.

Here is the code:

	rows, err := database.Query(`SELECT artists.name, songs.name, albums.name, COUNT(*) as count FROM songs LEFT JOIN albums ON songs.album = albums.id LEFT JOIN artists ON albums.artist = artists.id WHERE date>=date('2022-01-01') GROUP BY songs.name ORDER BY count DESC`)
	if err != nil {
		log.Fatal(err)
	}

	table = fmt.Sprintf("| Artist | Song | Album | Plays |\n---\n")
	for rows.Next() {
		rows.Scan(&artistName, &songName, &albumName, &plays)
		table += fmt.Sprintf("| %s | %s | %s | %s |\n", artistName, songName, albumName, plays)
	}

	out, err = glamour.Render(table, "dark")
	fmt.Print(out)
	rows.Close()
	database.Close()

I attached a screenshot of the output. The first is the glamour output and right below is the table variable printed as it is.
scr-2022-03-08-10-47-21

Your separator doesn't look right. It should probably read:

| Artist | Song | Album | Plays |
| --- | --- | --- | --- |
| Pure Wrath | Years of Silence | Hymn to the Woeful Hearts | 1 |
| Dio | When a Woman Cries | Dream Evil | 1 |
| Intestine Baalism | Tyrant | An Anatomy of the Beast | 1 |
| Amorphis | The Wolf | Halo | 1 |
| Amorphis | The Moon | Halo | 1 |