I am trying to figure out what method is called when I show a variable in an "html/template" template in Go via {{ .SomeVariable }}.
I am using the package "html/template".
I am using this function to render a template:
func renderTemplate(w http.ResponseWriter, tmpl string, p *Page) {
t, _ := template.ParseFiles("public/" + tmpl + ".html")
t.Execute(w, p)
}
with
type Page struct {
Title string
Users []*model.User
}
and an example template
<html>
<head>
<title>Listing Users</title>
</head>
<body>
<h1>Listing users</h1>
{{range .Params}}
<h3>
id {{.Id }}
email {{.Email}}
name {{.Name}}
</h3>
{{end}}
</body>
</html>
We store Id in a certain way and have a .String() method defined for displaying it.
When we use the package "text/template" the Id attribute displays correctly but when we use "html/template" it does not. My guess is that the former is calling .String() when displaying a variable and latter is not. I haven't been able to glean from the documentation what method is being called.
This is the first SO question I've ever written for Go. Hopefully made it clear but feel free to ask for additional info as I am a complete Go noob.
Thanks.
I use Gorilla sessions (via negroni-sessions) to store my user sessions in cookies. I also use github.com/unrolled/render for my HTML template rendering:
main.go:
package main
import (
...
"github.com/codegangsta/negroni"
"github.com/goincremental/negroni-sessions"
"github.com/goincremental/negroni-sessions/cookiestore"
"github.com/julienschmidt/httprouter"
"github.com/unrolled/render"
...
)
func init() {
...
ren = render.New(render.Options{
Directory: "templates",
Layout: "layout",
Extensions: []string{".html"},
Funcs: []template.FuncMap{TemplateHelpers},
IsDevelopment: false,
})
...
}
func main() {
...
router := httprouter.New()
router.GET("/", HomeHandler)
// Add session store
store := cookiestore.New([]byte("my password"))
store.Options(sessions.Options{
//MaxAge: 1200,
Domain: "",
Path: "/",
})
n := negroni.New(
negroni.NewRecovery(),
sessions.Sessions("cssession", store),
negroni.NewStatic(http.Dir("../static")),
)
n.UseHandler(router)
n.Run(":9000")
}
As you can see above, I use a layout.html master HTML template which is included when any page renders, like my home page:
package main
import (
"html/template"
"github.com/julienschmidt/httprouter"
)
func HomeHandler(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
var model = struct {
CatalogPicks []PromotionalModelList
ClearanceItems []Model
}{
CatalogPicks: GetCatalogPicks(),
ClearanceItems: GetClearanceItems(),
}
ren.HTML(w, http.StatusOK, "home", model)
}
In my layout.html master HTML template, I want to render an admin menu but only if the current user is an admin:
layout.html:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>{{ template "title" . }}</title>
...
</head>
<body>
...
<!--Main Menu-->
<nav class="menu">
<ul class="catalog">
<li class="has-submenu">
{{ RenderMenuCategories }}
</li>
<li>Blog</li>
<li>Company</li>
{{ RenderAdminMenu }}
</ul>
</nav>
...
My issue is that the above template helper function RenderAdminMenu() doesn't have access to the HTTP Request object and therefore cannot access the User session object to determine if the user is admin.
I can pass the User object into the template context via the Home page handler, and use an if statement RenderAdminMenu() function, like this
{{ if .User.IsAdmin }}
{{ RenderAdminMenu }}
{{ end }}
...but since I am using a master template, I would have to do that from every web page on the site. Is there a more efficient way?
I was thinking perhaps there might be a way to access some kind of global Context object from within RenderAdminMenu() (or layout.html) which contains the Request details (like you can in ASP.NET)
There's a few things you need to do to tie this together. I'm not going to show a complete example as it would be both fairly lengthy and may not match your code (which you haven't posted). It will contain the basic building blocks though: if you get stuck, come back with a direct question and a code snippet and you'll get a more direct answer :)
Write some middleware or logic in a [login] handler that saves the user data in the session when a user logs in. A userID, email and admin boolean value would be sufficient. e.g.
// In your login handler, once you've retrieved the user &
// matched their password hash (scrypt, of course!) from the DB.
session.Values["user"] = &youruserobject
err := session.Save(r, w)
if err != nil {
// Throw a HTTP 500
}
Note: remember that you need to gob.Register(&youruserobject{}) as per the gorilla/sessions docs if you want to store your own types.
Write a helper to type-assert your type when you pull it out of the session, e.g.
var ErrInvalidUser= errors.New("invalid user stored in session")
func GetUser(session *sessions.Session) (*User, error) {
// You can make the map key a constant to avoid typos/errors
user, ok := session.Values["user"].(*User)
if !ok || user == nil {
return nil, ErrInvalidUser
}
return user, nil
}
// Use it like this in a handler that serves user content
session, err := store.Get("yoursessionname", r)
if err != nil {
// Throw a HTTP 500
}
user, err := GetUser(session)
if err != nil {
// Re-direct back to the login page or
// show a HTTP 403 Forbidden, etc.
}
Write something to check if the returned user is an admin:
func IsAdmin(user *User) bool {
if user.Admin == true && user.ID != "" && user.Email != "" {
return true
}
return false
}
Pass that to the template:
err := template.Execute(w, "sometemplate.html", map[string]interface{}{
"admin": IsAdmin(user),
"someotherdata": someStructWithData,
}
// In your template...
{{ if .admin }}{{ template "admin_menu" }}{{ end }}
Also make sure you're setting an authentication key for your session cookies (read the gorilla docs), preferably an encryption key, and that you're serving your site over HTTPS with the Secure: true flag set as well.
Keep in mind that the above method is also simplified: if you de-flag a user as admin in your DB, the application will continue to detect them as an administrator for as long as their session lasts. By default this can be 7 days, so if you're in a risky environment where admin churn is a real problem, it may pay to have really short sessions OR hit the DB inside the IsAdmin function just to be safe. If it's a personal blog and it's just you, not so much.
Added: If you want to pass the User object directly to the template, you can do that too. Note that it's more performant to do it in your handler/middleware than it is in the template logic. You also get the flexibility of more error handling, and the option of "bailing out" earlier - i.e. if the session contains nothing, you can fire up a HTTP 500 error rather than rendering half a template or having to put lots of logic in your template to handle nil data.
You still need to store your User object (or equivalent) in the session, and retrieve it from session.Values before you can pass it to the template.
func GetUser(r *http.Request) *User {
session, err := store.Get("yoursessionname", r)
if err != nil {
// Throw a HTTP 500
}
if user, ok := session.Values["user"].(*User); ok {
return user
}
return nil
}
// In the handler itself
err := template.Execute(w, "sometemplate.html", map[string]interface{}{
"user": GetUser(r),
"someotherdata": someStructWithData,
}
// In your template...
{{ if .User.admin }}{{ template "admin_menu" }}{{ end }}
It seems you cannot access the Request context from a template or a template helper function afterall (so I accepted the answer above). My solution was to create a Page struct that I pass as the context for every template. It contains the Content as a generic interface, the User object, as well as other useful parameters:
//Page holds the model to be rendered for every HTTP handler.
type Page struct {
MetaTitle string
User User
HeaderStyles string
HeaderScripts string
FooterScripts string
Content interface{}
}
func (pg *Page) Init(r *http.Request) {
if pg.MetaTitle == "" {
pg.MetaTitle = "This is the default <title> content for the page!"
}
user, _ := GetUserFromSession(r)
pg.User = *user
if user.IsAdmin() {
pg.HeaderStyles += `<link href="/css/libs/summernote/summernote.css" rel="stylesheet">`
pg.FooterScripts += `<script src="/js/libs/summernote/summernote.min.js"></script>`
}
}
The Init method allows me to set defaults and use the Page struct more easily, by specifying only the Content for the page, if that's all I need:
package main
import (
"html/template"
"github.com/julienschmidt/httprouter"
)
func HomeHandler(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
var model = struct {
CatalogPicks []PromotionalModelList
ClearanceItems []Model
}{
CatalogPicks: GetCatalogPicks(),
ClearanceItems: GetClearanceItems(),
}
pg := &Page{Content: model}
pg.Init(r)
ren.HTML(w, http.StatusOK, "home", pg)
}
Sorry im beginner and i read golang.docs but didnt understand well.
i`ve : index.html:
<html>
<head>
</head>
<body>
<form action type="checkbox" name="test" value="A" {{.checked}}>
<input type="submit" value="save">
</body>
</html>
in main.go
if user click save button then check checkbox redirect that page and show checkbox checked
You could send variables in map. For example:
package main
import (
"bytes"
"fmt"
"text/template"
)
func main() {
t, _ := template.New("hi").Parse("Hi {{.name}}")
var doc bytes.Buffer
t.Execute(&doc, map[string]string{"name": "Peter"})
fmt.Println(doc.String()) //Hi Peter
}
The . is defined in go code.
Please provide the snippet of your go code where the template is executed, something like the following codes:
t, _ := template.ParseFiles(tmpl + ".html")
t.Execute(w, data) // the data must feature the field "checked"
Or
templates.ExecuteTemplate(w, tmpl+".html", data) // the data must feature the field "checked"
You can pass any type(interface{}) to a functions that execute a template as "data". Usually it is a Struct or a Map[string]string.
How to set the checked
Probably the "checked" is setted in the main.go at handler according to the posted form.
Read the docs and explain it better. Please
I've got this simple go lang webserver that does nothing more but parsing some data into an external HTML file and serve that file to the webserver.
package main
import (
"html/template"
"net/http"
)
type Event struct {
Name string
}
func handler(w http.ResponseWriter, r *http.Request) {
e := Event{ Name: "Melt! Festival" }
t, _ := template.ParseFiles("events.html")
t.Execute(w, e)
}
func main() {
http.HandleFunc("/", handler)
http.ListenAndServe(":1337", nil)
}
But whenever I try to parse the HTML file with the set it parses my html-page as text in stead of rendering the HTML in the browser
<!DOCTYPE>
<html>
<head>
<title>Event</title>
</head>
<body>
<p>
Event: {{.Name}}
</p>
</body>
</html>
When I leave the <!DOCTYPE> out of the HTML-file it renders it just fine.
Can anyone tell me why this is because I'm really curious? I spent two hours searching for the cause of my go code not working.
Your doctype declaration is incorrect, thus having an effect opposite from the desired one : it is probably interpreted by the browser as signifying the document isn't HTML.
Use this :
<!DOCTYPE html>
See reference.
Have you tried using DOCTYPE html in your file instead?
I wrote a very basic web application, following this tutorial. I want to add css rules in an external stylesheet, but it's not working - when the HTML templates are rendered, something goes wrong and the CSS is completely ignored. If I put the rules in tags, it works, but I don't want to have to deal with that.
In a Go web application, how do I render an external CSS stylesheet?
Add a handler to handle serving static files from a specified directory.
eg. create {server.go directory}/resources/ and use
http.Handle("/resources/", http.StripPrefix("/resources/", http.FileServer(http.Dir("resources"))))
along with /resources/somethingsomething.css
The reason for using StripPrefix is that you can change the served directory as you please, but keep the reference in HTML the same.
eg. to serve from /home/www/
http.Handle("/resources/", http.StripPrefix("/resources/", http.FileServer(http.Dir("/home/www/"))))
Note that this will leave the resources directory listing open.
If you want to prevent that, there is a good snippet on the go snippet blog:
http://gosnip.posterous.com/disable-directory-listing-with-httpfileserver
Edit: Posterous is now gone, so I just pulled the code off of the golang mailing list and will post it here.
type justFilesFilesystem struct {
fs http.FileSystem
}
func (fs justFilesFilesystem) Open(name string) (http.File, error) {
f, err := fs.fs.Open(name)
if err != nil {
return nil, err
}
return neuteredReaddirFile{f}, nil
}
type neuteredReaddirFile struct {
http.File
}
func (f neuteredReaddirFile) Readdir(count int) ([]os.FileInfo, error) {
return nil, nil
}
Original post discussing it: https://groups.google.com/forum/#!topic/golang-nuts/bStLPdIVM6w
And use it like this in place of the line above:
fs := justFilesFilesystem{http.Dir("resources/")}
http.Handle("/resources/", http.StripPrefix("/resources/", http.FileServer(fs)))