HTML templates in golang -
i'm next tutorial: golang tutorial - wiki , i've managed working except lastly point in "other task" section. implementation of tutorial:
package main import ( "fmt" "io/ioutil" "net/http" "html/template" "regexp" ) type page struct { title string body []byte } func (p *page) save() error { filename := "data/" + p.title + ".txt" homecoming ioutil.writefile(filename, p.body, 0600) } func loadpage(title string) (*page, error) { filename := "data/" + title + ".txt" body, err := ioutil.readfile(filename) if err != nil { homecoming nil, err } homecoming &page{title: title, body: body}, nil } func rendertemplate(w http.responsewriter, tmpl string, p *page) { t, _ := template.parsefiles("template/" + tmpl + ".html"); t.execute(w, p) } func viewhandler(w http.responsewriter, r *http.request) { title := r.url.path[len("/view/"):] p, err := loadpage(title) if err != nil { http.redirect(w, r, "/edit/" + title, http.statusfound); homecoming } expr := regexp.mustcompile(`\[.+\]`) p.body = expr.replaceallfunc(p.body, func ( match []byte) []byte { homecoming []byte("<a href='/view/" + string(match) + "'>" + string(match) + "</a>") }) rendertemplate(w, "view", p); } func savehandler(w http.responsewriter, r *http.request) { title := r.url.path[len("/save/"):] body := r.formvalue("body") p := &page{title: title, body: []byte(body)} p.save() http.redirect(w, r, "/view/" + title, http.statusfound) } func edithandler(w http.responsewriter, r *http.request) { title := r.url.path[len("/edit/"):] p, err := loadpage(title); if err != nil { p = &page{title: title} } rendertemplate(w, "edit", p); } func main() { http.handlefunc("/", func(w http.responsewriter, r *http.request) { http.redirect(w, r, "/view/index", http.statusfound) }) http.handlefunc("/view/", viewhandler) http.handlefunc("/edit/", edithandler) http.handlefunc("/save/", savehandler) http.listenandserve(":8080", nil) fmt.println("running"); }
html/template engine prints anchor tag expected, escapes html entities. i've not been able find appropriate way of doing it.
use template.html mark body safe html.
the next function converts body html.
// move package-level variable it's compile once. var linkpat = regexp.mustcompile(`\[.+\]`) func tohtml(s string) template.html { // escape in string first ensure // special characters ('<' example) displayed // characters , not treated markup. s = template.htmlescapestring(s) // insert links. s = linkpat.replaceallstringfunc(s, func(m string) string { s = s[1 : len(s)-1] homecoming "<a href='/view/" + m + "'>" + m + "</a>" }) homecoming template.html(s) }
render page using:
rendertemplate(w, "edit", map[string]interface{}{ "title": p.body, "body": tohtml(p.body), })
html templates go
No comments:
Post a Comment