本文整理汇总了Golang中html/template.Template.Execute方法的典型用法代码示例。如果您正苦于以下问题:Golang Template.Execute方法的具体用法?Golang Template.Execute怎么用?Golang Template.Execute使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类html/template.Template
的用法示例。
在下文中一共展示了Template.Execute方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: mkHttpHandler
func mkHttpHandler(h Handler, tpl *template.Template) http.HandlerFunc {
return func(rw http.ResponseWriter, req *http.Request) {
sess, err := getSess(req)
if err != nil {
req.Cookies()
log.Printf("Error while getting session: %s", err)
rw.Write([]byte("Unable to create a session. Try reloading the page or delete the cookies for this site."))
}
user := userFromSess(sess)
outdata, user := h(user, sess, req)
mail := ""
if user != nil {
mail = user.Email()
}
if err := sess.Save(req, rw); err != nil {
log.Printf("Error while saving session: %s", err)
}
if err := tpl.Execute(rw, &tpldata{mail, outdata}); err != nil {
log.Printf("Error executing template %s: %s", tpl.Name(), err)
}
}
}
示例2: executeTemplate
func (s *server) executeTemplate(t *template.Template, context interface{}) ([]byte, error) {
var buf bytes.Buffer
if err := t.Execute(&buf, context); err != nil {
return nil, err
}
return buf.Bytes(), nil
}
示例3: actionHome
func actionHome(w http.ResponseWriter, req *http.Request) {
var templActionHome *template.Template = template.Must(
template.ParseGlob("templates/home/*.html"))
lay := getLayoutTemplates()
wr := &HtmlContainer{}
// templActionHome.Funcs(template.FuncMap{"len": Len})
data := HtmlAssigner{
"List": getEntryList("", 10),
"Test": "Test",
}
err := templActionHome.Execute(wr, data)
if err != nil {
fmt.Errorf("%v", err)
}
lay.New("title").Parse("Najnowsze wpisy - " + config.GetStringDef("page", "title", ""))
err = lay.Execute(w, wr.getHtml())
if err != nil {
fmt.Errorf("%v", err)
}
}
示例4: RunTemplate
func RunTemplate(reportFilename, templateFile, templateText string, out *os.File, data interface{}, format string) (err error) {
var tmpl *template.Template
var htmpl *htemplate.Template
if templateFile != "" {
if format == "html" {
htmpl, err = htemplate.New(templateFile).ParseGlob(templateFile)
} else {
tmpl, err = template.New(templateFile).ParseGlob(templateFile)
}
} else {
if format == "html" {
htmpl, err = htemplate.New(reportFilename).Parse(templateText)
} else {
tmpl, err = template.New(reportFilename).Parse(templateText)
}
}
if err != nil {
return err
}
if format == "html" {
err = htmpl.Execute(out, data)
} else {
err = tmpl.Execute(out, data)
}
if err != nil {
return err
}
return err
}
示例5: main
func main() {
var err error
var tpl *template.Template
tpl, err = tpl.ParseGlob("templates/*.gohtml")
if err != nil {
log.Fatalln(err)
}
err = tpl.Execute(os.Stdout, Page{
Title: "My Title 2",
Body: "hello world",
})
if err != nil {
log.Fatalln(err)
}
fmt.Println("\n***************")
err = tpl.ExecuteTemplate(os.Stdout, "tpl.gohtml", Page{
Title: "My Title 2",
Body: "hello world",
})
if err != nil {
log.Fatalln(err)
}
fmt.Println("\n***************")
err = tpl.ExecuteTemplate(os.Stdout, "tpl2.gohtml", Page{
Title: "My Title 2",
Body: "hello world",
})
if err != nil {
log.Fatalln(err)
}
}
示例6: ExecTpl
// ExecTpl is a utility function to execute the template that may be removed shortly in the future.
func ExecTpl(w http.ResponseWriter, tpl *template.Template, data interface{}) {
err := tpl.Execute(w, data)
if err != nil {
w.Write([]byte("Error executing template: " + err.Error()))
}
return
}
示例7: dirList
func dirList(w http.ResponseWriter, f File, name string, tmpl *template.Template) {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
var contents []string
for {
dirs, err := f.Readdir(100)
if err != nil || len(dirs) == 0 {
break
}
for _, d := range dirs {
name := d.Name()
if d.IsDir() {
name += "/"
}
contents = append(contents, name)
}
}
tmpl.Execute(w, &struct {
Name string
Contents []string
}{
Name: name,
Contents: contents,
})
}
示例8: Execute
/**
* execute template
*
*
* @param wr
* @param value
* @return error
*/
func (l *Template) Execute(wr io.Writer, value TemplateValue) error {
var resultErr error
// TODO 待整改
tplName := value.TplName
tplPath := value.TplPath
if 0 != len(tplName) {
// 模版名称查询缓存模版
if tmpl := l.goTemplate.Lookup(tplName); nil != tmpl {
resultErr = tmpl.Execute(wr, value.Data)
} else {
resultErr = errors.New("\"" + tplName + "\" name not found template.")
}
} else if 0 != len(tplPath) {
// 模版路径解析模版
var tmpl *template.Template = nil
tmpl, resultErr = l.Parse(tplPath)
if nil == resultErr && nil != tmpl {
resultErr = tmpl.Execute(wr, value.Data)
} else if nil == resultErr {
resultErr = errors.New(tplPath + " template parse error.")
}
} else {
resultErr = errors.New("TemplateValue tplName or tplPath is nil(len == 0)")
}
return resultErr
}
示例9: httpHandler
func httpHandler(w http.ResponseWriter, r *http.Request) {
//>> for debug
var httpTemplate *template.Template = nil
var httpContentCache []byte = nil
//<<
var err error
if httpTemplate == nil {
httpTemplate, err = template.ParseFiles(getTemplateFilePath("home.html"))
if err != nil {
sendPageData(w, []byte("Parse template error."), "text/plain; charset=utf-8")
return
}
}
if httpContentCache == nil {
var buf bytes.Buffer
err = httpTemplate.Execute(&buf, nil)
if err != nil {
sendPageData(w, []byte("Render page error."), "text/plain; charset=utf-8")
return
}
httpContentCache = buf.Bytes()
}
sendPageData(w, httpContentCache, "text/html; charset=utf-8")
}
示例10: writer
func (ws *WebSocker) writer(conn *websocket.Conn, user string, tmpl *template.Template) {
pingTicker := time.NewTicker(pingPeriod)
chl, chq := notifier.listen(user)
ws.log.Println(user, "connected")
defer func() {
pingTicker.Stop()
conn.Close()
close(chq)
ws.log.Println(user, "disconnected")
}()
for {
var buf bytes.Buffer
select {
case p := <-chl:
conn.SetWriteDeadline(time.Now().Add(writeWait))
buf.Reset()
if err := tmpl.Execute(&buf, p); err != nil {
ws.log.Println(err)
return
}
if err := conn.WriteMessage(websocket.TextMessage, buf.Bytes()); err != nil {
return
}
ws.log.Println("notified:", user)
case <-pingTicker.C:
conn.SetWriteDeadline(time.Now().Add(writeWait))
if err := conn.WriteMessage(websocket.PingMessage, []byte{}); err != nil {
ws.log.Println("ping:", err)
return
}
}
}
}
示例11: HTML
// HTML parses the Ace templates and renders HTML to the response writer.
func (r *renderer) HTML(status int, name string, v interface{}, opts *ace.Options) {
var basePath, innerPath string
paths := strings.Split(name, ":")
basePath = paths[0]
if len(paths) > 1 {
innerPath = paths[1]
}
tplc, errc := r.p.Load(basePath, innerPath, opts)
var tpl *template.Template
select {
case tpl = <-tplc:
case err := <-errc:
http.Error(r, err.Error(), http.StatusInternalServerError)
return
}
buf := new(bytes.Buffer)
if err := tpl.Execute(buf, v); err != nil {
http.Error(r, err.Error(), http.StatusInternalServerError)
return
}
r.Header().Set(render.ContentType, defaultContentType)
r.WriteHeader(status)
io.Copy(r, buf)
}
示例12: Execute
//Execute runs the template with the specified context attaching all the block
//definitions in the files that match the given globs sending the output to
//w. Any errors during the compilation of any files that have to be compiled
//(see the discussion on Modes) or during the execution of the template are
//returned.
func (t *Template) Execute(w io.Writer, ctx interface{}, globs ...string) (err error) {
if t.dirty || compile_mode == Development {
err = t.Compile()
if err != nil {
return
}
}
//grab a read lock to make sure we dont get a half compiled template
t.compile_lock.RLock()
defer t.compile_lock.RUnlock()
var tmpl *template.Template
if len(globs) > 0 {
tmpl, err = t.getCachedGlobs(globs)
if err != nil {
return
}
} else {
tmpl = t.t
}
err = tmpl.Execute(w, ctx)
return
}
示例13: GetIndexPageV1Handler
//GetIndexPageV1Handler is the index page of Dockyard web.
//When with params `/?ac-discovery=1` means access from `rkt trust --prefix={domain}` possibility.
//Other access maybe come from web browser, and will generate HTML page then return.
func GetIndexPageV1Handler(ctx *macaron.Context) (int, []byte) {
var t *template.Template
var err error
discovery := ctx.Query("ac-discovery")
//Generate GPG html response from template.
//TODO: Use the setting or environment parameter with GPG html template.
//TODO: Use the const parameter instead of `1`, wow the ac-discovery value is only 1.
if len(discovery) > 0 && discovery == "1" {
if t, err = template.ParseGlob("views/aci/gpg.html"); err != nil {
log.Errorf("[%s] get gpg file template status: %s", ctx.Req.RequestURI, err.Error())
result, _ := json.Marshal(map[string]string{"Error": "Get GPG File Template Status Error"})
return http.StatusBadRequest, result
}
t.Execute(ctx.Resp, map[string]string{"Domains": setting.Domains})
//TODO: Complete the http response.
}
//TODO: Generate index html page.
return http.StatusOK, []byte("")
}
示例14: renderBaseHtml
func renderBaseHtml(handler Handler, base string, tmpl string, data map[string]interface{}) (err error) {
var t *template.Template
if base != "" {
baseBytes, err := ioutil.ReadFile(tplPath + base)
if err != nil {
panic(err)
}
t, err = templates[tmpl].Clone()
if err != nil {
panic(err)
}
t, err = t.Parse(string(baseBytes))
if err != nil {
panic(err)
}
} else {
t = templates[tmpl]
}
user, ok := currentUser(handler.Request)
if ok {
data["username"] = user.Username
data["servers"] = master.app
}
err = t.Execute(handler.ResponseWriter, data)
check(err)
return
}
示例15: actionCategories
func actionCategories(w http.ResponseWriter, req *http.Request) {
var templActionCategories *template.Template = template.Must(
template.ParseGlob("templates/categories/*.html"))
wr := &HtmlContainer{}
// templActionHome.Funcs(template.FuncMap{"len": Len})
data := HtmlAssigner{
"List": category.GetTagCloud(),
"Test": "Test",
}
err := templActionCategories.Execute(wr, data)
if err != nil {
fmt.Errorf("%v", err)
}
lay := getLayoutTemplates()
lay.New("title").Parse("Lista Kategorii - " + config.GetStringDef("page", "title", ""))
err = lay.Execute(w, wr.getHtml())
if err != nil {
fmt.Errorf("%v", err)
}
}