I have a question!
How convert to markdown "Body" row in sql foreach and add to array?
type post struct {
Id int
Title string
Body string
Tags string
Time string
BodyHtml string
}
func indexHandler(w http.ResponseWriter, r *http.Request) {
// Query
rows, _ := db.Query("SELECT * FROM liamka_me_posts LIMIT 2")
defer rows.Close()
posts := []post{}
for rows.Next() {
p := post{}
rows.Scan(&p.Id, &p.Title, &p.Body, &p.Tags, &p.Time)
p.Body = html.UnescapeString(ConvertMarkdownToHtml(p.Body))
fmt.Println(p.Body)
posts = append(posts, p)
}
t.ExecuteTemplate(w, "index", posts)
}
PS: Added UnescapeString in line. In console it shows like <p>HELLO</p>
, but when render page it show <p><strong>HELLO!</strong></p>
I think the problem in your code is in the using &p.Body
(pointer) instead of p.Body
. Try it:
p.Body = string(blackfriday.MarkdownCommon([]byte(p.Body)))
Also I think you want to save result of convertion into p.BodyHtml
instead of p.Body
.
You have to make conversation before you add result to array (slice), because append
will add a copy of your structure into array (slice). Or you can use a pointer in your array (slice).
So, finally:
type post struct {
Id int
Title string
Body string
Tags string
Time string
BodyHtml string
}
for rows.Next() {
p := post{}
rows.Scan(&p.Id, &p.Title, &p.Body, &p.Tags, &p.Time)
p.BodyHtml = string(blackfriday.MarkdownCommon([]byte(p.Body)))
posts = append(posts, p)
}
As elithrar noticed, to prevent escaping HTML-specific data, use template.HTML
type instead of string
on that data.