1 回答
TA贡献1993条经验 获得超5个赞
在完整代码下方,借助模板自定义函数,我能够做到这一点:
package main
import (
"html/template"
"net/http"
)
type User struct {
Flags []flag //string
Title string
}
type UsersPageData struct {
PageTitle string
Users []User
}
type flag int
const (
Admin flag = iota + 1 // iota = 0
Editer
Superuser
Viewer
Dummy
)
func subtract(arg1, arg2 int) int {
return arg1 - arg2
}
func helloHandler(name string) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Map the `subtract` custom function in the template
funcMap := map[string]interface{}{"subtract": subtract}
master := []flag{Admin, Editer, Superuser, Viewer}
admin := []flag{Admin, Superuser, Viewer}
user := []flag{Viewer, Dummy}
tmpl := template.New("").Funcs(template.FuncMap(funcMap))
template.Must(tmpl.ParseFiles("index.html"))
data := UsersPageData{
PageTitle: "Users list: ",
Users: []User{
{Flags: master, Title: "Everything"},
{Flags: admin, Title: "Administrator"},
{Flags: user, Title: "Normal user"},
},
}
tmpl.ExecuteTemplate(w, "index.html", data)
})
}
func main() {
fs := http.StripPrefix("/www/", http.FileServer(http.Dir("./www")))
http.Handle("/www/", fs)
http.Handle("/", helloHandler("John"))
http.ListenAndServe(":8080", nil)
}
是index.html:
<html>
{{/* This is a comment
{{$flags := []flag{Admin, Editer, Superuser, Viewer};}}
Admin Flag = iota + 1 // iota = 0
Editer
Superuser
Viewer
}}
*/}}
<ul>
{{range .Users}}
<span>{{.Title}}</span>
{{ $done := false}} {{$length := len .Flags}}
{{range $i, $v := .Flags}}
{{ if $done }}
{{ else }}
{{if or (eq $v 1) (eq $v 3)}}
<input type="text" name="subject" placeholder= {{$v}} required>
{{ $done = true }}
{{else}}
{{ if eq $i (subtract $length 1)}}
<input type="text" name="subject" placeholder= {{$v}} disabled>
{{ end }}
{{end}}
{{end}}
{{end}}
{{end}}
</ul>
</html>
- 1 回答
- 0 关注
- 90 浏览
添加回答
举报