Reputation: 33
I am trying to create html email content in Go using go templates. Inside the html email content I need to store JSON data like this:
<script type ="application/ld+json">
[
{ JSON Object},
{ JSON Object}
]
</script>
Unfortunately, I can not figure out how to do this with go lang. This is what I have tried so far:
tr, err := template.New("tr").Parse("<html><body><script type=\"application/ld+json\">{{.}}</script></body></html>")
if err != nil {
log.Fatal(err)
}
var doc bytes.Buffer
err = tr.Execute(&doc, template.HTML(emailModel))
if err != nil {
log.Fatal(err)
}
emailHtmlContent := doc.String()
fmt.Println(emailHtmlContent)
When I execute this, the JSON is stored in "" double quotes of a string. If I use a <pre>
tag the double quotes are not shown but I need to store the JSON in a script tag.
Is there a way to pull this off?
Thanks alread!
Upvotes: 1
Views: 1436
Reputation: 2625
you can use text/template
instead, it will not escape strings.
package main
import (
"bytes"
"encoding/json"
"fmt"
"log"
"text/template"
)
type Student struct {
Id string `json:"id"`
Name string `json:"name"`
}
func main() {
emailModel, err := json.Marshal(Student{Id: "m", Name: "k"})
if err != nil {
log.Fatal(err)
}
tr, err := template.New("tr").Parse("<html><body><script type=\"application/ld+json\">{{.}}</script></body></html>")
if err != nil {
log.Fatal(err)
}
var doc bytes.Buffer
err = tr.Execute(&doc, string(emailModel))
if err != nil {
log.Fatal(err)
}
emailHtmlContent := doc.String()
fmt.Println(emailHtmlContent)
}
Upvotes: 2