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

时间:2016-08-06 12:26:31

标签: html mysql go go-templates

我在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>

我错过了什么吗?

2 个答案:

答案 0 :(得分:3)

在这里,您可以使用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上的示例。

答案 1 :(得分:1)

要在浏览器中打印此内容,请将[ { url: "nigeria.php", country: "Nigeria", city_code: "ABV", total_fare: "376", arrival_to: "ABV" }, { url: "ghana.php", country: "Ghana", city_code: "ACC", total_fare: "312", arrival_to: "ACC" }, { url: "south-africa.php", country: "South Africa", city_code: "BFN", total_fare: "432", arrival_to: "BFN" } ] 替换为例如\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>

我希望这会有所帮助。