Gir*_*iri 5 html mysql go go-templates
我在 MySQL 中存储了一些内容,如下所示。
"Hi!\nHow are you?\nHere is the link you wanted:\nhttp://www.google.com"
Run Code Online (Sandbox Code Playgroud)
当我在 Golang 模板中打印它时,它无法正确解析。我的意思是所有内容都显示在一行中。
它应该像这样打印
Hi!
How are you?
Here is the link you wanted:
http://www.google.com
Run Code Online (Sandbox Code Playgroud)
这是我的模板代码。
<tr>
<td>TextBody</td>
<td>{{.Data.Content}}</td>
</tr>
Run Code Online (Sandbox Code Playgroud)
我错过了什么吗?
小智 2
要在浏览器中打印此内容,请替换\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
}
Run Code Online (Sandbox Code Playgroud)
要查看输出,请运行此代码并打开浏览器http://127.0.0.1/
另请参阅: html/templates - 用 <br> 替换换行符
我希望这有帮助。