本文整理匯總了Golang中html/template.Must函數的典型用法代碼示例。如果您正苦於以下問題:Golang Must函數的具體用法?Golang Must怎麽用?Golang Must使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。
在下文中一共展示了Must函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。
示例1: init
func init() {
ALL_METHODS = []string{GET, HEAD, POST, CONNECT, DELETE, OPTIONS, PUT, TRACE}
defaultMimeTypes = make(map[string]string)
defaultMimeTypes[".htm"] = MIME_TYPE_HTML
defaultMimeTypes[".html"] = MIME_TYPE_HTML
defaultMimeTypes[".xhtml"] = MIME_TYPE_XHTML_XML
defaultMimeTypes[".xml"] = MIME_TYPE_XML
defaultMimeTypes[".css"] = MIME_TYPE_CSS
defaultMimeTypes[".js"] = MIME_TYPE_JAVASCRIPT
defaultMimeTypes[".json"] = MIME_TYPE_JSON
defaultMimeTypes[".jpg"] = MIME_TYPE_JPEG
defaultMimeTypes[".jpeg"] = MIME_TYPE_JPEG
defaultMimeTypes[".gif"] = MIME_TYPE_GIF
defaultMimeTypes[".png"] = MIME_TYPE_PNG
defaultMimeTypes[".ico"] = MIME_TYPE_ICO
defaultMimeTypes[".swf"] = MIME_TYPE_SWF
defaultMimeTypes[".zip"] = MIME_TYPE_ZIP
defaultMimeTypes[".bz2"] = MIME_TYPE_BZIP2
defaultMimeTypes[".gz"] = MIME_TYPE_GZ
defaultMimeTypes[".tar"] = MIME_TYPE_TAR
defaultMimeTypes[".tgz"] = MIME_TYPE_GZ
defaultMimeTypes[".htc"] = MIME_TYPE_COMPONENT
defaultMimeTypes[".manifest"] = MIME_TYPE_CACHE_MANIFEST
defaultMimeTypes[".svg"] = MIME_TYPE_SVG
defaultMimeTypes[".txt"] = MIME_TYPE_TEXT_PLAIN
defaultMimeTypes[".text"] = MIME_TYPE_TEXT_PLAIN
defaultMimeTypes[".csv"] = MIME_TYPE_CSV
var err error
HTML_DIRECTORY_LISTING_SUCCESS_TEMPLATE, err = template.New("directory_listing_success").Parse(HTML_DIRECTORY_LISTING_SUCCESS_TEMPLATE_STRING)
template.Must(HTML_DIRECTORY_LISTING_SUCCESS_TEMPLATE, err)
HTML_DIRECTORY_LISTING_ERROR_TEMPLATE, err = template.New("directory_listing_error").Parse(HTML_DIRECTORY_LISTING_ERROR_TEMPLATE_STRING)
template.Must(HTML_DIRECTORY_LISTING_ERROR_TEMPLATE, err)
}
示例2: InitAdminTemplates
func InitAdminTemplates() {
serverPage = template.Must(template.ParseFiles("views/admin/templates/server.html"))
banlogsTempl = template.Must(template.ParseFiles("views/admin/templates/ban_logs.html"))
chatLogsTempl = template.Must(template.ParseFiles("views/admin/templates/chatlogs.html"))
lobbiesTempl = template.Must(template.ParseFiles("views/admin/templates/lobbies.html"))
adminPageTempl = template.Must(template.ParseFiles("views/admin/index.html"))
}
示例3: Login
func (c *Controller) Login() (string, error) {
var pool_tech_works int
funcMap := template.FuncMap{
"noescape": func(s string) template.HTML {
return template.HTML(s)
},
}
data, err := static.Asset("static/templates/login.html")
if err != nil {
return "", err
}
modal, err := static.Asset("static/templates/modal.html")
if err != nil {
return "", err
}
t := template.Must(template.New("template").Funcs(funcMap).Parse(string(data)))
t = template.Must(t.Parse(string(modal)))
b := new(bytes.Buffer)
// есть ли установочный пароль и был ли начально записан ключ
var setupPassword bool
if !c.Community {
setupPassword_, err := c.Single("SELECT setup_password FROM config").String()
if err != nil {
return "", err
}
myKey, err := c.GetMyPublicKey(c.MyPrefix)
if err != nil {
return "", err
}
if len(myKey) == 0 && (len(setupPassword_) > 0 || setupPassword_ == string(utils.DSha256(""))) {
setupPassword = true
}
}
//fmt.Println(c.Lang)
// проверим, не идут ли тех. работы на пуле
if len(c.NodeConfig["pool_admin_user_id"]) > 0 && c.NodeConfig["pool_admin_user_id"] != utils.Int64ToStr(c.UserId) && c.NodeConfig["pool_tech_works"] == "1" && c.Community {
pool_tech_works = 1
} else {
pool_tech_works = 0
}
err = t.ExecuteTemplate(b, "login", &loginStruct{
Lang: c.Lang,
MyModalIdName: "myModalLogin",
UserID: c.UserId,
PoolTechWorks: pool_tech_works,
SetupPassword: setupPassword,
Community: c.Community,
Desktop: utils.Desktop(),
Mobile: utils.Mobile()})
if err != nil {
return "", err
}
return b.String(), nil
}
示例4: init
func init() {
http.HandleFunc("/", authOnly(root))
http.HandleFunc("/sign", authOnly(sign))
guestbookTemplate = template.Must(template.ParseFiles("tmpl/index.tmpl"))
signinTemplate = template.Must(template.ParseFiles("tmpl/signin.tmpl"))
}
示例5: TestTemplate_FuncMap_url
func TestTemplate_FuncMap_url(t *testing.T) {
app := kocha.NewTestApp()
funcMap := template.FuncMap(app.Template.FuncMap)
func() {
tmpl := template.Must(template.New("test").Funcs(funcMap).Parse(`{{url "root"}}`))
var buf bytes.Buffer
if err := tmpl.Execute(&buf, nil); err != nil {
panic(err)
}
actual := buf.String()
expected := "/"
if !reflect.DeepEqual(actual, expected) {
t.Errorf("Expect %q, but %q", expected, actual)
}
}()
func() {
tmpl := template.Must(template.New("test").Funcs(funcMap).Parse(`{{url "user" 713}}`))
var buf bytes.Buffer
if err := tmpl.Execute(&buf, nil); err != nil {
panic(err)
}
actual := buf.String()
expected := "/user/713"
if !reflect.DeepEqual(actual, expected) {
t.Errorf("Expect %v, but %v", expected, actual)
}
}()
}
示例6: TestRender
func TestRender(t *testing.T) {
driverNames := [...]string{"file", "memory"}
for _, v := range driverNames {
d, err := render.New(v, map[string]string{
"dir": "./_testdata",
})
if err != nil {
t.Fatal(err)
}
d.AddCommonTpl("base.html")
tpl := template.Must(d.GetTemplate("index.html"))
buf := &bytes.Buffer{}
tpl.Execute(buf, map[string]string{
"Title": "標題",
"Content": "內容",
})
if testdata1 != buf.String() {
t.Fatalf("Content not equal %q", v)
}
_ = template.Must(d.GetTemplate("index1.html"))
}
}
示例7: CompileUserTemplates
func CompileUserTemplates() {
usersTemplates = template.Must(layout.Clone()).Funcs(template.FuncMap{
"sliceBy12": func(problems []models.Problem) [][]models.Problem {
slices := make([][]models.Problem, 0, len(problems)/12+1)
for i := 0; i+11 < len(problems); i += 12 {
slice := make([]models.Problem, 12)
for j := i; j < i+12; j++ {
slice[j] = problems[i+j]
}
slices = append(slices, slice)
}
if len(problems)%12 != 0 {
slice := make([]models.Problem, len(problems)%12)
for i := 0; i < len(problems)%12; i++ {
slice[i] = problems[len(problems)-len(problems)%12+i]
}
slices = append(slices, slice)
}
return slices
},
})
usersTemplates = template.Must(usersTemplates.ParseGlob("./templates/users/*.html"))
}
示例8: errorHandler
// Handle errors here, this allows us to control the format of the output rather
// than using http.Error() defaults
func errorHandler(w http.ResponseWriter, r *http.Request, status int, err string) {
w.WriteHeader(status)
switch status {
case http.StatusNotFound:
logHandler("ERROR", fmt.Sprintf("client %s tried to request %v", r.RemoteAddr, r.URL.Path))
page := template.Must(template.ParseFiles(
"static/_base.html",
"static/404.html",
))
if err := page.Execute(w, nil); err != nil {
errorHandler(w, r, http.StatusInternalServerError, err.Error())
return
}
case http.StatusInternalServerError:
logHandler("ERROR", fmt.Sprintf("an internal server error occured when %s requested %s with error:\n%s", r.RemoteAddr, r.URL.Path, err))
page := template.Must(template.ParseFiles(
"static/_base.html",
"static/500.html",
))
if err := page.Execute(w, nil); err != nil {
// IF for some reason the tempalets for 500 errors fails, fallback
// on http.Error()
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
}
示例9: serveCmd
func serveCmd() {
var err error
// load and parse templates
baseTmplPath := *templatePath + "/base.html"
tmplHome = template.Must(template.ParseFiles(*templatePath+"/home.html", baseTmplPath))
tmplAccount = template.Must(template.ParseFiles(*templatePath+"/account.html", baseTmplPath))
//tmplLogout = template.Must(template.ParseFiles(*templatePath+"/logout.html", baseTmplPath))
//tmplNewUser = template.Must(template.ParseFiles(*templatePath+"/newuser.html", baseTmplPath))
tmplUser = template.Must(template.ParseFiles(*templatePath+"/user.html", baseTmplPath))
tmplBomView = template.Must(template.ParseFiles(*templatePath+"/bom_view.html", baseTmplPath))
tmplBomUpload = template.Must(template.ParseFiles(*templatePath+"/bom_upload.html", baseTmplPath))
if err != nil {
log.Fatal(err)
}
openBomStore()
openAuthStore()
openPricingSource()
// serve template static assets (images, CSS, JS)
http.Handle("/static/", http.FileServer(http.Dir(*templatePath+"/")))
http.Handle("/favicon.ico", http.FileServer(http.Dir(*templatePath+"/static/")))
// fall through to default handler
http.HandleFunc("/", baseHandler)
listenString := fmt.Sprintf("%s:%d", *listenHost, *listenPort)
http.ListenAndServe(listenString, nil)
fmt.Println("Serving at " + listenString)
}
示例10: init
func init() {
layout, err := ioutil.ReadFile("templates/layout.html")
if err != nil {
log.Fatal("Could not read layout:", err)
}
files, err := filepath.Glob("templates/*")
if err != nil {
log.Fatal("Could not glob templates:", err)
}
for _, f := range files {
if filepath.Base(f) == "layout.html" {
continue
}
content, err := ioutil.ReadFile(f)
if err != nil {
log.Fatalf("Could not read %q: %v", f, err)
}
t := template.New("page")
t.Funcs(map[string]interface{}{
"toEuros": func(x int) float64 {
return float64(x) / 100
},
})
t = template.Must(t.Parse(string(layout)))
template.Must(t.New("content").Parse(string(content)))
parsedTemplates[filepath.Base(f)] = t
}
}
示例11: errorHandler
func errorHandler(w http.ResponseWriter, r *http.Request, status int, err string) {
w.WriteHeader(status)
page := template.Must(template.ParseFiles(
"static/_base.html",
"static/baseError.html",
))
switch status {
case http.StatusNotFound:
page = template.Must(template.ParseFiles(
"static/_base.html",
"static/404.html",
))
case http.StatusInternalServerError:
page = template.Must(template.ParseFiles(
"static/_base.html",
"static/500.html",
))
case http.StatusUnauthorized:
page = template.Must(template.ParseFiles(
"static/_base.html",
"static/401.html",
))
}
if err := page.Execute(w, nil); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
示例12: reports
func reports(c *appcontext.AppContext, w http.ResponseWriter, r *http.Request) (int, error) {
SetCache(w, 60*60)
report := r.FormValue("report")
var (
p Page
err error
)
if report == "items" || report == "" {
templates.Templates = template.Must(template.ParseFiles("templates/reports/items.html", "templates/reports.html", templates.LayoutPath))
err = templates.Templates.ExecuteTemplate(w, "base", p)
} else if report == "itemTrends" {
templates.Templates = template.Must(template.ParseFiles("templates/reports/itemTrends.html", "templates/reports.html", templates.LayoutPath))
err = templates.Templates.ExecuteTemplate(w, "base", p)
} else if report == "telVar" {
templates.Templates = template.Must(template.ParseFiles("templates/reports/telVar.html", "templates/reports.html", templates.LayoutPath))
err = templates.Templates.ExecuteTemplate(w, "base", p)
} else if report == "ap" {
templates.Templates = template.Must(template.ParseFiles("templates/reports/ap.html", "templates/reports.html", templates.LayoutPath))
err = templates.Templates.ExecuteTemplate(w, "base", p)
} else if report == "guilds" {
templates.Templates = template.Must(template.ParseFiles("templates/reports/guilds.html", "templates/reports.html", templates.LayoutPath))
err = templates.Templates.ExecuteTemplate(w, "base", p)
}
if err != nil {
return http.StatusInternalServerError, err
}
return http.StatusOK, nil
}
示例13: checkEnvironment
// checkEnvironment checks if required dirs and files exist, uses defaults if not.
func checkEnvironment() {
_, err := os.Stat(dataDir)
if err != nil {
if os.IsNotExist(err) {
err = os.Mkdir(dataDir, 0644)
if err != nil {
fmt.Println(`Unable to create "notes" directory:`, err)
os.Exit(0)
}
} else {
fmt.Println(`Unable to check existence of "notes" directory:`, err)
os.Exit(0)
}
}
_, err = os.Stat(templatesDir)
if err != nil {
if os.IsNotExist(err) {
// Template dir does not exist
fmt.Println("Using default templates.")
templates = template.Must(template.New("index.html").Parse(defaultTemplateIndexHtml))
template.Must(templates.New("view.html").Parse(defaultTemplateViewHtml))
template.Must(templates.New("edit.html").Parse(defaultTemplateEditHtml))
template.Must(templates.New("error.html").Parse(defaultTemplateErrorHtml))
}
} else {
fmt.Println("Using file templates.")
templates = template.Must(template.ParseFiles(
templatesDir+"index.html",
templatesDir+"view.html",
templatesDir+"edit.html",
templatesDir+"error.html"))
}
}
示例14: HomeHandler
func HomeHandler(w http.ResponseWriter, r *http.Request) {
tmpl := template.New("base")
template.Must(tmpl.Parse(BaseTmpl))
template.Must(tmpl.Parse(ConfigTemp))
nodes := GetScattrData()
tmpl.Execute(w, nodes)
}
示例15: viewHandler
func viewHandler(w http.ResponseWriter, r *http.Request) {
entries := Store.AllEntries()
tmpl := template.New("base")
template.Must(tmpl.Parse(BaseTmplStr))
template.Must(tmpl.Parse(ViewTmplStr))
tmpl.Execute(w, entries)
}