1

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!

2

1 Answer 1

2

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)
}
Sign up to request clarification or add additional context in comments.

1 Comment

Great. Thanks. Exactly what I was looking for

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.