Rendering html/template (Beginner)

I need help on rendering html templates on an existing page.

I’ll appreciate a sample code.
Cheers.

Please run through this tutorial: https://golang.org/doc/articles/wiki/#tmp_6 and then read http://jan.newmarch.name/go/template/chapter-template.html

If you get stuck, post your code and I’m sure we can help.

Okay, thanks.
The issue is actually passing in new variables to an html template.

I’ll revert when I have to.

Cheers.

Can you show what (the code) you have tried so far?

I haven’t tried any yet, I can only render static html templates like this

t, _ = t.parseFiles(“learn.html”)
t.Execute(w, nil)

I understand this…

But, I’m still trying to fifure out how to pass variables like this

{{ .value}}

The book you shared is helping.

first, you must have {{.Value}} not {{.value}} in your template file. also, you must create a struct which contain Value field in your main go file and a properly variable

type Page struct {
    Value string
}
var p Page

in your main function you can use something like this to read template

t = template.New("templ")
t.ParseGlob("*.html")

then in the place you want to render template use

t.ExecuteTemplate(w, "learn.html", p)

Thanks geosoft… I got an error from “value” and changed to Value.

How can this code work. From the first page, I want the post(from the form) method to render a new page. Code compiles but the conval.html is not rendered.

Same code in the screenshot

Is this a wrong practice?

func serveComment(writer http.ResponseWriter, request *http.Request){
if request.Method == “GET”{
t, _ := template.ParseFiles(“comment.html”)
t.Execute(writer, nil)
}else{
request.ParseForm()
// render
u := currentUser.Nick
ucomment := request.FormValue(“talk”)
// commTime := time.Now().String()

    dude := Comment{
        Person: Person{
            Nick: u,
        },
        value: ucomment,
    }
    t, err := template.ParseFiles("comval.html")
    if err != nil{
        log.Fatal(err)
    }

    err = t.Execute(writer, dude)
    if err != nil{
        log.Fatal(err)
    }
}

}

You are basically on the right track with templates. I have another suggestion, though.

Since you are inside of a function that does HTTP handling, it is not a good idea to do log.Fatal(..), in my opinion. Fatal will exit your program, which is not what you want. See: https://golang.org/pkg/log/#Fatal

Instead, use the Error function from the http package. See the documentation: https://golang.org/pkg/net/http/#Error

So, do this instead

    err = t.Execute(writer, dude)
    if err != nil{
        http.Error(writer, "Could not render template.", 500)
        return  // required to stop further writes to response
    }

Finally, it is easier to read your code if it is in Markdown format, instead of screenshots. :smile:

3 Likes

comval.html is not rendered more probably because has some syntax errors.

on the other hand @coleman has right about log.Fatal usage but in your particular case log.Fatal can be used because without a valid template your code wont work properly. so i think that another good practice can be putting the template parsing somewhere in the main function not in the http handler.

You missed a naked return (I’ve added it) If you miss that, your handler continues, potentially trying to write to the ResponseWriter again and corrupting it.

1 Like

Run through the entire tutorial I linked: Writing Web Applications - The Go Programming Language

It shows how to pass data to a template.

<h1>Editing {{.Title}}</h1>

<form action="/save/{{.Title}}" method="POST">
<div><textarea name="body" rows="20" cols="80">{{printf "%s" .Body}}</textarea></div>
<div><input type="submit" value="Save"></div>
</form>

(I’ve simplified the code below to make it even clearer)

func editHandler(w http.ResponseWriter, r *http.Request) {
    title := r.PostForm("title")
    p := &Page{Title: title}
    t, err := template.ParseFiles("edit.html")
    if err != nil {
        // Only expose your errors publicly in development 
        http.Error(w, err.Error(), 500)
        return
    }
    t.Execute(w, p)
}
1 Like

Thanks a lot, I have been taking my time to look at your solutions and they have been helpful. I’ll always refer to them, when need be.

Cheers.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.