如何在 Golang 模板中打印新行?

How to print new lines in Golang template?

我在 MySQL 中存储了一些内容,如下所示。

"Hi!\nHow are you?\nHere is the link you wanted:\nhttp://www.google.com"

当我在 Golang 模板中打印它时,它没有正确解析。我的意思是所有内容都显示在一行中。

它应该像这样打印

Hi!
How are you?
Here is the link you wanted:
http://www.google.com

这是我的模板代码。

<tr>
    <td>TextBody</td>
    <td>{{.Data.Content}}</td>
</tr>

我错过了什么吗?

这里可以使用Split函数解析字符串,并使用sep作为分隔符将子字符串分割成片。

package main

import (
    "fmt"
    "strings"
)

func main() {
    txt := "Hi!\nHow are you?\nHere is the link you wanted:\nhttp://www.google.com"
    res := strings.Split(txt, "\n")
    for _, val := range res {
        fmt.Println(val)
    }
}

输出将是:

Hi!
How are you?
Here is the link you wanted:
http://www.google.com

示例 Go Playground

要在浏览器中打印此内容,请将 \n 替换为例如<br>
喜欢 body = strings.Replace(body, "\n", "<br>", -1)
请参阅此工作示例代码:

package main

import (
    "bytes"
    "fmt"
    "html/template"
    "log"
    "net/http"
    "strings"
)

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

func ServeHTTP(w http.ResponseWriter, r *http.Request) {
    html := `
<!DOCTYPE html>
<html>
<body>  
<table style="width:100%">
  <tr>
    <th>Data</th>
    <th>Content</th> 
  </tr> 
  <tr>
    <td>{{.Data}}</td>
    <td>{{.Content}}</td>
  </tr>
</table> 
</body>
</html>
`
    st := "Hi!\nHow are you?\nHere is the link you wanted:\nhttp://www.google.com"
    data := DataContent{"data", st}

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

type DataContent struct {
    Data, Content string
}

要查看输出,运行 此代码并在 http://127.0.0.1/

打开浏览器

另见:html/templates - Replacing newlines with <br>

希望对您有所帮助。