user1091558 user1091558 - 6 months ago 50
MySQL Question

How to print new lines in Golang template?

I have stored some content in MySQL that looks like this.

"Hi!\nHow are you?\nHere is the link you wanted:\n"

When I print it in Golang template, its not parsing correctly. I mean everything displayed in one line.

Its supposed to print like this

How are you?
Here is the link you wanted:

Here is my template code.


Am I missing something?

Amd Amd

To print this in browser, replace \n with e.g. <br>
like body = strings.Replace(body, "\n", "<br>", -1)
See this working sample code:

package main

import (

func main() {
    http.HandleFunc("/", ServeHTTP)
    if err := http.ListenAndServe(":80", nil); err != nil {

func ServeHTTP(w http.ResponseWriter, r *http.Request) {
    html := `
<!DOCTYPE html>
<table style="width:100%">
    st := "Hi!\nHow are you?\nHere is the link you wanted:\n"
    data := DataContent{"data", st}

    buf := &bytes.Buffer{}
    t := template.Must(template.New("template1").Parse(html))
    if err := t.Execute(buf, data); err != nil {
    body := buf.String()
    body = strings.Replace(body, "\n", "<br>", -1)
    fmt.Fprint(w, body)

type DataContent struct {
    Data, Content string

To see the output, run this code and open your browser at

Also see: html/templates - Replacing newlines with <br>

I hope this helps.