I'm using the html/template package to serve a template on submission of the form. The page that is a copy of that template is being rendered with the location of the template-file instead of the text that should replace {{ .Title }}
So in response.html, the {{ .Title }} is showing up as "Projects/Go/src/web/site/index" instead of "I feel that is "
How can I get the {{ .Title }} to be replaced by the text and not the file-location?
Here is my code:
package main
import (
"fmt"
"net/http"
"github.com/zenazn/goji"
"github.com/zenazn/goji/web"
"html/template"
"io/ioutil"
)
type Page struct {
Title string
Body []byte
}
func loadPage(title string) (*Page, error){
filename := title + ".html"
body, err := ioutil.ReadFile(filename)
if err != nil{
return nil, err
}
return &Page{Title: title, Body: body}, nil
}
func renderTemplate(w http.ResponseWriter, tmpl string, p *Page){
t, err := template.ParseFiles(tmpl + ".html")
if err != nil{
panic(err)
}
err = t.Execute(w, p)
fmt.Println(err)
}
func response(c web.C, w http.ResponseWriter, r *http.Request){
p, err := loadPage("Projects/Go/src/web/site/index")
if err != nil{
p = &Page{Title: "I feel that is "}
panic(err)
}
renderTemplate(w, "Projects/Go/src/web/site/response", p)
}
func serveSingle(filename string) func(w http.ResponseWriter, r *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, filename)
}
}
func main() {
goji.Get("/", serveSingle("Projects/Go/src/web/site/index.html"))
goji.Handle("/ask", response)
goji.Serve()
}
Your loadPage()
function sets Page.Title
to the file path, minus the .html
extension by default.
You are only overriding this default behaviour in your response()
function when err != nil
. You're also completely overriding the p
variable with the line p = &Page{Title: "I feel that is "}
instead of just setting the Title
field on the existing Page
.
You should try changing:
func response(c web.C, w http.ResponseWriter, r *http.Request){
p, err := loadPage("Projects/Go/src/web/site/index")
if err != nil{
p = &Page{Title: "I feel that is "}
panic(err)
}
renderTemplate(w, "Projects/Go/src/web/site/response", p)
}
To:
func response(c web.C, w http.ResponseWriter, r *http.Request){
p, err := loadPage("Projects/Go/src/web/site/index")
if err != nil{
panic(err)
}
p.Title = "I feel that is "
renderTemplate(w, "Projects/Go/src/web/site/response", p)
}