本文整理汇总了Golang中html/template.ParseFiles函数的典型用法代码示例。如果您正苦于以下问题:Golang ParseFiles函数的具体用法?Golang ParseFiles怎么用?Golang ParseFiles使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了ParseFiles函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: RenderTemplate
func RenderTemplate(w http.ResponseWriter, tmpl string, arg interface{}) {
skel, err := template.ParseFiles(fmt.Sprintf("%s/skeleton.html", templatesDir))
if err != nil {
log.Println("Error when parsing a template: %s", err)
return
}
content, err := template.ParseFiles(fmt.Sprintf("%s/%s.html", templatesDir, tmpl))
if err != nil {
log.Println("Error when parsing a template: %s", err)
return
}
buff := &bytes.Buffer{}
err = content.Execute(buff, arg)
if err != nil {
log.Println("Error when executing a template: %s", err)
return
}
c := template.HTML(buff.String())
page := &Page{Content: c}
err = skel.Execute(w, page)
if err != nil {
log.Println("Error when executing a template: %s", err)
return
}
}
示例2: 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
}
}
}
示例3: Login
// Login template
func (ctrl *Access) Login(w http.ResponseWriter, r *http.Request) {
if r.Method == "GET" {
t := template.Must(template.ParseFiles("views/layouts/application.htm", "views/login/login.htm"))
if err := t.Execute(w, &Access{}); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
} else {
r.ParseForm()
user := ctrl.Auth(r.Form["username"][0], r.Form["password"][0])
if user != nil {
t := template.Must(template.ParseFiles("views/layouts/application.htm", "views/login/info.htm"))
page := &Access{LoginPage: &LoginPage{UserName: r.Form["username"][0], HasVideoAccess: user.HasVideoAccess}}
if err := t.Execute(w, page); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
} else {
http.Error(w, "Auth", http.StatusForbidden)
}
}
}
示例4: excute
func (this *Pages) excute() (err error) {
buffer := bytes.NewBufferString("")
if this.NotFoundPath == "" {
defaultTemplate.Execute(buffer, struct{ Body string }{not_found_body})
} else {
notFoundTemplate, err := template.ParseFiles(this.NotFoundPath)
if err != nil {
return err
}
notFoundTemplate.Execute(buffer, nil)
}
this.notFound = buffer.String()
buffer = bytes.NewBufferString("")
if this.InternalErrorPath == "" {
defaultTemplate.Execute(buffer, struct{ Body string }{internal_error_body})
} else {
internalErrorTemplate, err := template.ParseFiles(this.InternalErrorPath)
if err != nil {
return err
}
internalErrorTemplate.Execute(buffer, nil)
}
this.internalError = buffer.String()
return
}
示例5: treeOperations
func treeOperations(w http.ResponseWriter, r *http.Request) {
if r.Method == "POST" {
err := r.ParseForm()
if err != nil {
io.WriteString(w, fmt.Sprintf("Error parsing the submitted form:\n%s", err))
}
var v int
v, err = strconv.Atoi(r.Form["number"][0])
if err != nil {
io.WriteString(w, fmt.Sprintf("Error parsing the given number:\n%s", err))
}
if r.Form["insert"] != nil {
fmt.Printf("\nInserting [%d]\n", v)
btree = Insert(btree, v)
} else if r.Form["delete"] != nil {
fmt.Printf("\nDeleting [%d]\n", v)
btree = Delete(btree, v)
} else {
io.WriteString(w, "Neither an insert request, nor a delete request")
return
}
renderer := PrintbTree(btree, r.Form["numbers"][0])
err =
template.Must(template.ParseFiles("treedisplay.html")).Execute(w, &renderer)
if err != nil {
io.WriteString(w, fmt.Sprintf("Error generating HTML file from the template:\n%s", err))
return
}
} else {
/* The next if loop is a hack to avoid re-initialization due to
* the GET request that will come when the page gets rendered
* during the response of the POST (the above block) */
if btree == nil {
btree, _ = InitializebTree(3)
fmt.Println("Initializing the btree")
for _, v := range []int{6, 1, 3, 10, 4, 7, 8, 9, 18, 12, 13,
19, 15, 22, 33, 35, 44, 70, 37, 38, 39, 50, 60, 55, 80,
90, 101, 102, 100, 110, 120, 57, 58} {
btree = Insert(btree, v)
}
renderer := PrintbTree(btree, "")
err :=
template.Must(template.ParseFiles("treedisplay.html")).Execute(w, &renderer)
if err != nil {
io.WriteString(w, fmt.Sprintf("Error generating HTML file from the template:\n%s", err))
return
}
}
}
}
示例6: 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"))
}
示例7: RenderWithHttpCode
// for now, render templates directly to easier edit them.
func (h *TemplateRenderer) RenderWithHttpCode(w http.ResponseWriter, output_writer io.Writer, http_code int, template_name string, p interface{}) bool {
var err error
if output_writer == nil {
output_writer = w
}
if h.doCache {
templ := h.cachedTemplates.Lookup(template_name)
if templ == nil {
return false
}
setContentTypeFromTemplateName(template_name, w.Header())
w.WriteHeader(http_code)
err = templ.Execute(output_writer, p)
} else {
t, err := template.ParseFiles(h.baseDir + "/" + template_name)
if err != nil {
t, err = template.ParseFiles(h.baseDir + "/component/" + template_name)
if err != nil {
log.Printf("%s: %s", template_name, err)
return false
}
}
setContentTypeFromTemplateName(template_name, w.Header())
w.WriteHeader(http_code)
err = t.Execute(output_writer, p)
}
if err != nil {
log.Printf("Template broken %s (%s)", template_name, err)
return false
}
return true
}
示例8: addCourse
func addCourse(w http.ResponseWriter, r *http.Request) {
if r.Method == "GET" {
t, _ := template.ParseFiles("addCourse.gtpl")
t.Execute(w, nil)
} else {
r.ParseForm()
year := r.FormValue("nianDu")
course := r.FormValue("keCheng")
item := r.FormValue("shiYangXiangMu")
teacher := r.FormValue("zhiDaoJiaoShi")
class := r.FormValue("banJi")
student_num, err := strconv.Atoi(r.FormValue("renShu"))
if err != nil {
fmt.Println("学生人数转换失败。")
panic(err)
}
class_num, err := strconv.Atoi(r.FormValue("xueShi"))
if err != nil {
fmt.Println("学时数转换失败。")
panic(err)
}
group_num, err := strconv.Atoi(r.FormValue("fenZu"))
if err != nil {
fmt.Println("分组数转换失败。")
panic(err)
}
property := r.FormValue("shiYanXingZhi")
dt := r.FormValue("riQi")
bg := r.FormValue("kaiShi")
ed := r.FormValue("jieShu")
staff := r.FormValue("staff")
note := r.FormValue("note")
if staff == "" {
staff = "张海宁"
}
id := bson.NewObjectId()
e := &Course{id, year, course, item, teacher, class, student_num, class_num,
group_num, property, dt, bg, ed, staff, note}
session, err := mgo.Dial("localhost")
if err != nil {
fmt.Println("建立连接出错了。")
panic(err)
}
defer session.Close()
session.SetMode(mgo.Monotonic, true)
c := session.DB("lab").C("course")
err2 := c.Insert(e)
fmt.Println("添加成功了。")
if err2 != nil {
fmt.Println("插入出错了。")
panic(err2)
}
// fmt.Fprintln(w, "添加", name, "成功。")
time.Sleep(5000)
t, _ := template.ParseFiles("addCourse.gtpl")
t.Execute(w, nil)
}
}
示例9: login
func login(w http.ResponseWriter, r *http.Request) {
fmt.Println("method:", r.Method)
r.ParseForm()
if r.Method == "GET" {
t, _ := template.ParseFiles("login.gtpl")
t.Execute(w, nil)
} else {
usr := r.Form["usr"]
pwd := r.Form["pwd"]
fmt.Println("username", usr)
fmt.Println("password", pwd)
session, err := mgo.Dial("localhost:27017")
if err != nil {
panic(err)
}
defer session.Close()
session.SetMode(mgo.Monotonic, true)
c := session.DB("test").C("person")
err = c.Insert(&Person{usr, pwd})
if err != nil {
panic(err)
}
// fmt.Fprintln(w, "登陆成功。")
t, _ := template.ParseFiles("query.gtpl")
t.Execute(w, nil)
}
}
示例10: requestAddDecoratorHandler
func requestAddDecoratorHandler(w http.ResponseWriter, r *http.Request) {
decI, _ := iFDec2(r)
fieldId := sFField(r)
idf, _ := iFField(r)
predefinedDec := decorators[decI]
pDec := decorators[decI]
if pDec.Params == nil {
t, _ := template.ParseFiles("./template/addDecorator.html")
field := &SyncField{Id: idf}
iDB.Preload("Decorators").First(field)
d := &Decorator{}
d.DecoratorId = decI
d.Params = ""
d.SyncFieldId = idf
d.SortingOrder = len(field.Decorators) + 1
d.Name = predefinedDec.Name
d.Description = predefinedDec.Description
field.Decorators = append(field.Decorators, *d)
iDB.Save(field)
t.Execute(w, field)
} else {
t, _ := template.ParseFiles(pDec.Template)
rac := &RequestAddContent{}
rac.FieldId = idf
rac.DecoratorId = decI
rac.PDecorator = decorators[decI]
t.Execute(w, rac)
}
http.Redirect(w, r, "/editSyncField/"+fieldId, http.StatusNotFound)
}
示例11: 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"))
}
示例12: letmein
func letmein(w http.ResponseWriter, r *http.Request) {
if r.Method == "GET" {
header(w, nil)
t, _ := template.ParseFiles("login.gtpl")
t.Execute(w, nil)
footer(w, nil)
} else {
r.ParseForm()
user := r.FormValue("usr")
pwd := r.FormValue("pwd")
if user != "gmsft" || pwd != "891012" {
time.Sleep(2)
header(w, nil)
t, _ := template.ParseFiles("login.gtpl")
t.Execute(w, nil)
footer(w, nil)
} else {
t, _ := template.ParseFiles("index.gtpl")
t.Execute(w, nil)
}
}
}
示例13: 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)
}
示例14: 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
}
}
示例15: 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
}