rince chacko
rince chacko

Reputation: 49

Pass a string to template in golang

I've been scouring the internet and can't find much at all about posting to html template and form in golang . This is my attempt at it

my error cannot use "html/template".HTML(" login") (type "html/template".HTML) as type string in argument to "html/template ".New("foo").Parse

i want to pass a value to {{.ErrorMessage}} in html file

My HTML (login.html)

{{ define "content"}}
<h2> {{.ErrorMessage}}</h2>


form action="/login" method="POST">
Username:input type="username" name="username">
Password:input type="password" name="password">
input type="submit" value="Submit">
/form>

{{end}}

{{define "extra_head"}} <title>Title</title>{{end}}
{{define "nav"}}{{end}}


{{define "extra_footer"}}<footer>[email protected]</footer>{{end}}
{{template "_layout.html" .}}

MAIN.G0

package main

import (

"net/http"
"ere.com/handlers"
)

func main() {
http.HandleFunc("/register", handlers.RegisterHandler) // setting router rule
http.HandleFunc("/sucess", handlers.RegisterSucessHandler)
http.HandleFunc("/login", handlers.LoginHandler)
http.HandleFunc("/update", handlers.UpdateHandler)
http.HandleFunc("/logout", handlers.LogoutHandler)
http.HandleFunc("/header", handlers.HeaderHandler)


if err := http.ListenAndServe(":8181", nil); err != nil {
    //log.Fatal("http.ListenAndServe: ", err)
}


}

handler int

    package handlers
      import (
      "html/template"
       )

func GetTemplate(name string) *template.Template{
tmpl := template.Must(template.ParseFiles(
    "frontend/templates/_layout.html",
    "frontend/templates/" + name + ".html",
))


return tmpl
}

LoginHandler

    type viewModel    struct {
Id          bson.ObjectId
Email       string
Password    string
FirstName   string
LastName    string
ErrorMessage    string
}
    func LoginHandler (response http.ResponseWriter, request *http.Request) {
viewModel:=viewmodels.RegisterViewModel{}

if (request.Method == "POST") {

    request.ParseForm()
    user := models.User{}
    user.Email = request.Form.Get("username")
    user.Password = request.Form.Get("password")
    boolUser, userID := user.FindUserDB()

    if (boolUser != true) {

        viewModel.ErrorMessage = "incorrect username or password"

      //need help here

        t, err := template.New("foo").Parse(template.HTML("login"))
        err = t.ExecuteTemplate(response, "T", viewModel)


        err := GetTemplate("login").Execute(response, nil, )

        if err != nil {
            panic(err)
        }

    }else {

        setSession(userID, response)
        http.Redirect(response, request, "/update", 302)
    }


}else {
    err := GetTemplate("login").Execute(response, nil,)

    if err != nil {
        panic(err)
    }

}

Upvotes: 4

Views: 21171

Answers (1)

icza
icza

Reputation: 418505

The error is in this line:

t, err := template.New("foo").Parse(template.HTML("login"))

The template.Parse() method expects one argument of type string, and you pass it an argument of type template.HTML.

This: template.HTML("login") is a type conversion, it converts the string value "login" to type template.HTML. This is not needed. Simply use:

t, err := template.New("foo").Parse("login")

Although this is hardly what you want, you have to pass the template text to the Parse() method, not a file name! Most likely you wanted to call Template.ParseFiles().

In fact, since this is what follows (which is a syntax error btw):

err := GetTemplate("login").Execute(response, nil, )

You don't even need the line where you have error... so simply remove these 2 lines:

t, err := template.New("foo").Parse(template.HTML("login"))
err = t.ExecuteTemplate(response, "T", viewModel)

And looks you want to pass viewModel as the parameter to the template, so do so in the next line and remove the last comma , to make it compile:

err := GetTemplate("login").Execute(response, viewModel)

A word of advice: Do not parse templates in your handlers, very inefficient, instead parse them when your app starts, and just reuse the parsed templates. Read this question for more explanation:

It takes too much time when using "template" package to generate a dynamic web page to client in golang

Upvotes: 5

Related Questions