I am attempting to convert my "\n
" to "<br/>
" in my Golang templates.
type Page struct {
HTTPMethod string
Template string
CharSet string
Slug string
MetaTitle string
MetaDescription string
MetaKeywords string
Title string
Body string
Navigation Links
Detail interface{}
}
for _, page := range pages.Pages {
page := page
router.HandleFunc(page.Slug, func(w http.ResponseWriter, r *http.Request) {
err := tmpl.ExecuteTemplate(w, page.Template, page)// page of type Page
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
})
}
The template looks like:
{{define "index"}}{{template "header" . }}<h1>{{.Title}}</h1><div>{{.Body}}</div>{{template "footer"}}{{end}}
I attempted to concatenate the string with:
page.Body = "Some text." +htmlBRTag+ "More text"
Which outputs the following:
htmlBRTag := "<br/>" // -> <br/>
htmlBRTag = "<br/>" //-> <br/>
The expected outcome would be:
page.Body = "Some text.<br/>More text"
Any suggestions how to do this?
Below is replicable code that runs out of the box:
package main
import (
"fmt"
"html/template"
"log"
"net/http"
"github.com/gorilla/handlers"
"github.com/gorilla/mux"
)
type Data struct {
Field1 string
Field2 string
Field3 string
}
var tmpl *template.Template
func main() {
defer func() {
if r := recover(); r != nil {
fmt.Printf("Recovering from panic, error is: %v \n", r)
}
}()
router := mux.NewRouter()
port := ":8085"
htmlBreak := "<br/>"
data := Data{}
data.Field1 = "Some text<br/>More text"
data.Field2 = "Some text" + htmlBreak + "More text"
data.Field3 = template.HTMLEscapeString(data.Field2)
router.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
err := tmpl.ExecuteTemplate(w, "index", data)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
})
var err error
tmpl, err = template.ParseGlob("views/*")
if err != nil {
panic(err.Error())
}
router.PathPrefix("/").HandlerFunc(func(res http.ResponseWriter, req *http.Request) {
http.FileServer(http.Dir("./static/")).ServeHTTP(res, req)
})
fmt.Println("Server running on localhost" + port)
err = http.ListenAndServe(port, handlers.CompressHandler(router))
if err != nil {
log.Fatal(err)
}
}
And in the ./views folder I have index.html, index.html, footer.html
{{define "header"}}<!doctype html><html lang="en"><head><meta charset="utf-8"><title>Title</title></head><body>{{end}}
{{define "index"}}{{template "header" . }}
<div>F1: {{.Field1}}</div>
<div>F2: {{.Field2}}</div>
<div>F3: {{.Field3}}</div>
{{template "footer"}}{{end}}
{{define "footer"}}</body></html>{{end}}
The current output is:
F1: Some text<br/>More text
F2: Some text<br/>More text
F3: Some text<br/>More text
The expected outcome is a line break like:
Some text
More text
I tried the following:
htmlBRTag := "<br/>"
b = "Some text." +htmlBRTag+ "More text"
Page.Body = template.HTMLEscapeString(b)
The text in the template becomes:
Some text.<br/>More text