示例#1
1
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
}
示例#2
0
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)
		}
	}
}
示例#3
0
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
0
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
0
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
0
// 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
0
文件: fs.go 项目: twocool/srvdir
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
0
/**
 *	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
0
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
0
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
0
// 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
0
文件: tmplmgr.go 项目: goods/tmplmgr
//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
0
//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
0
文件: console.go 项目: mysll/flynet
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
0
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)
	}
}
示例#16
0
func (g *Group) execute(w io.Writer, layout string, t *template.Template, data interface{}) error {
	l, ok := g.dict[layout]
	if !ok {
		return fmt.Errorf(`layouts: missing layout "%s"`, layout)
	}

	buf := bytes.NewBuffer(make([]byte, 0, 1024))
	err := t.Execute(buf, data)
	if err != nil {
		return err
	}

	b, err := ioutil.ReadAll(buf)
	if err != nil {
		return err
	}

	l.Funcs(template.FuncMap{
		"content": makeContentFunc(template.HTML(bytes.TrimSpace(b))),
	})

	if l.Parent != "" {
		return g.execute(w, l.Parent, l.Template, data)
	} else {
		err = l.Execute(w, data)
		if err != nil {
			return err
		}
	}
	return nil
}
示例#17
0
文件: status.go 项目: 2722/lantern
// ErrorAccessingPage creates and returns a generic "error accessing page" error.
func ErrorAccessingPage(server string, errMessage error) ([]byte, error) {
	var err error
	var buf []byte
	var tmpl *template.Template

	if errMessage == nil {
		errMessage = errors.New("Unknown error.")
	}

	buf, err = Asset("generic_error.html")

	if err != nil {
		return nil, err
	}

	tmpl, err = template.New("status_error").Parse(string(buf))
	if err != nil {
		return nil, err
	}

	data := errorAccesingPageT{
		ServerName:   server,
		ErrorMessage: normalizeError(errMessage),
	}

	out := bytes.NewBuffer(nil)

	if err = tmpl.Execute(out, data); err != nil {
		return nil, err
	}

	return out.Bytes(), nil
}
示例#18
0
文件: webapp.go 项目: haegyung/tattoo
func (ctx *Context) Execute(tpl *template.Template, data interface{}) error {
	var err error
	ctx.Info.Message = "OK"
	ctx.Info.HttpCode = 200
	ctx.Application.AccessLog(ctx)
	ctx.Writer.Header().Set("Content-Type", "text/html")
	ctx.Writer.Header().Set("Connection", "keep-alive")
	ctx.Writer.Header().Set("Cache-Control", "must-revalidate, max-age=300")

	// overlay headers
	if ctx.Headers != nil {
		for k, v := range ctx.Headers {
			ctx.Writer.Header().Set(k, v)
		}
	}

	// compress ?
	if ctx.Info.UseGZip {
		gw := gzip.NewWriter(ctx.Writer)
		ctx.Writer.Header().Set("Content-Encoding", "gzip")
		err = tpl.Execute(gw, data)
		gw.Close()
	} else {
		err = tpl.Execute(ctx.Writer, data)
	}
	return err
}
示例#19
0
文件: context.go 项目: NeoChow/qor
func (context *Context) Execute(name string, result interface{}) {
	var tmpl *template.Template
	var cacheKey string

	if context.Action == "" {
		context.Action = name
	}

	if context.Resource != nil {
		cacheKey = path.Join(context.resourcePath(), name)
	} else {
		cacheKey = name
	}

	if t, ok := templates[cacheKey]; !ok || true {
		var err error
		tmpl = template.New("layout.tmpl").Funcs(context.FuncMap())
		if tmpl, err = context.FindTemplate(tmpl, "layout.tmpl"); err == nil {
			for _, name := range []string{"header", "footer"} {
				if tmpl.Lookup(name) == nil {
					tmpl, _ = context.FindTemplate(tmpl, name+".tmpl")
				}
			}
		}
	} else {
		tmpl = t
	}

	context.Content = context.Render(name, result)
	if err := tmpl.Execute(context.Writer, context); err != nil {
		fmt.Println(err)
	}
}
示例#20
0
func Render(field Field, attrs ...string) (template.HTML, error) {
	if reflect.ValueOf(field).IsNil() {
		return emptyHTML, nil
	}

	data := struct {
		Field  Field
		Attrs  []string
		Radios []template.HTML
	}{
		Field: field,
		Attrs: attrs,
	}

	var t *template.Template
	switch widget := field.Widget().(type) {
	case *HiddenWidget:
		return RenderField(field, attrs)
	case *CheckboxWidget:
		t = getTemplate(CheckboxTemplatePath)
	case *RadioWidget:
		data.Radios = widget.Radios(attrs, field.(SingleValueField).StringValue())
		t = getTemplate(RadioTemplatePath)
	default:
		t = getTemplate(WidgetTemplatePath)
	}

	buf := &bytes.Buffer{}
	if err := t.Execute(buf, data); err != nil {
		return emptyHTML, err
	}

	return template.HTML(buf.String()), nil
}
示例#21
0
文件: main.go 项目: x4rMa/admin-1
func (b *BaseField) BaseRender(w io.Writer, tmpl *template.Template, value interface{}, errStr string, startRow bool, ctx map[string]interface{}) {
	if ctx == nil {
		ctx = map[string]interface{}{}
	}
	ctx["label"] = b.Label
	ctx["blank"] = b.Blank
	ctx["name"] = b.Name
	ctx["value"] = value
	ctx["error"] = errStr
	ctx["help"] = b.Help
	ctx["startrow"] = startRow
	if b.Width == 0 {
		b.Width = 12
	}
	ctx["width"] = b.Width

	var buf bytes.Buffer
	tmpl.Execute(&buf, ctx)
	ctx["field"] = template.HTML(buf.String())

	err := fieldWrapper.Execute(w, ctx)
	if err != nil {
		fmt.Println(err)
	}
}
示例#22
0
func actionCategoryList(w http.ResponseWriter, req *http.Request) {

	Id := req.URL.Query().Get("id")
	fmt.Println(Id)

	// // param := req.Vars()
	// catId, ok := param["id"]
	// if ok == nil {
	// 	catId = 0
	// }

	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)
	}
}
示例#23
0
func applyTemplate(t *template.Template, name string, data interface{}) []byte {
	var buf bytes.Buffer
	if err := t.Execute(&buf, data); err != nil {
		log.Printf("%s.Execute: %s", name, err)
	}
	return buf.Bytes()
}
示例#24
0
func renderHTML(w http.ResponseWriter, r *http.Request, task types.EremeticTask, taskID string) {
	var err error
	var tpl *template.Template

	data := make(map[string]interface{})
	funcMap := template.FuncMap{
		"ToLower": strings.ToLower,
	}

	if task == (types.EremeticTask{}) {
		tpl, err = template.ParseFiles("templates/error_404.html")
		data["TaskID"] = taskID
	} else {
		tpl, err = template.New("task.html").Funcs(funcMap).ParseFiles("templates/task.html")
		data = makeMap(task)
	}

	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		log.Error(err.Error())
		return
	}

	err = tpl.Execute(w, data)
}
示例#25
0
func parseParametersTemplate(templatePath string, p parameters) (string, error) {
	f, err := os.Create(generatedParametersPath)
	if err != nil {
		return generatedParametersPath, errgo.Mask(err)
	}
	defer func() {
		if err := f.Close(); err != nil {
			panic(err)
		}
	}()

	absoluteParametersTemplatePath, err := filepath.Abs(templatePath)
	if err != nil {
		return "", errgo.Mask(err)
	}

	templateData, err := ioutil.ReadFile(absoluteParametersTemplatePath)
	if err != nil {
		return "", errgo.Mask(err)
	}

	var tmpl *template.Template
	if tmpl, err = template.New("cfg").Parse(string(templateData)); err != nil {
		return generatedParametersPath, errgo.Mask(err)
	}

	if err = tmpl.Execute(f, p); err != nil {
		return generatedParametersPath, errgo.Mask(err)
	}

	return generatedParametersPath, nil
}
示例#26
0
// submitPage is the submission page served on "/submit/"
func submitPage(w http.ResponseWriter, r *http.Request, t *template.Template) {
	if r.Method == "POST" {
		if r.FormValue("title") == "" || r.FormValue("content") == "" {
			http.Redirect(w, r, "/submit/", http.StatusFound)
			return
		}

		newEntry := &blog.BlogEntry{
			Title:   r.FormValue("title"),
			Content: r.FormValue("content"),
			Date:    time.Now(),
		}

		blogState.AddEntry(newEntry)
		sort.Sort(blog.ByDate{blogState.Entries})

		http.Redirect(w, r, "/", http.StatusFound)
	} else {
		err := t.Execute(w, nil)
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
	}
}
示例#27
0
// ApplyTemplate is internal. Gets a the template, clones and executes.
// getter is called after l.Init so it can rely on l.Template presence.
func (l *LazyTemplate) ApplyTemplate(getter func() (*template.Template, string), data interface{}) (*bytes.Buffer, error) {
	var clone *template.Template
	if err := func() error {
		l.MU.Lock()
		defer l.MU.Unlock()
		if err := l.Init(); err != nil {
			return err
		}
		var t *template.Template
		if getter == nil {
			t = l.Template
		} else {
			var name string
			t, name = getter()
			if t == nil {
				return fmt.Errorf("template: %q is undefined", name)
			}
		}
		var err error
		clone, err = t.Clone()
		return err
	}(); err != nil {
		return nil, err
	}
	buf := new(bytes.Buffer)
	err := clone.Execute(buf, data)
	return buf, err
}
示例#28
0
// mainPage is the main page served on "/"
func mainPage(w http.ResponseWriter, r *http.Request, t *template.Template) {
	if r.URL.String() == "/" {
		t.Execute(w, blogState)
	} else {
		http.NotFound(w, r)
		return
	}
}
示例#29
0
func RenderTemplateWithData(w io.Writer, r *http.Request, tpl *template.Template, data interface{}) error {
	err := tpl.Execute(w, data)
	if err != nil {
		return MakeHttpError(err, http.StatusInternalServerError, r)
	}

	return nil
}
示例#30
0
文件: http.go 项目: no2key/dex
func execTemplateWithStatus(w http.ResponseWriter, tpl *template.Template, data interface{}, status int) {
	w.WriteHeader(status)
	if err := tpl.Execute(w, data); err != nil {
		log.Errorf("Error loading page: %q", err)
		phttp.WriteError(w, http.StatusInternalServerError, "error loading page")
		return
	}
}