Пример #1
0
// Render takes a Beego context, template name and a Context (map[string]interface{}).
// The template is parsed and cached, and gets executed into beegoCtx's ResponseWriter.
//
// Templates are looked up in `templates/` instead of Beego's default `views/` so that
// Beego doesn't attempt to load and parse our templates with `html/template`.
func Render(beegoCtx *context.Context, tmpl string, ctx Context) {
	mutex.RLock()
	template, ok := templates[tmpl]
	mutex.RUnlock()

	if !ok || devMode {
		var err error

		// default ViewsPath
		prefix := beego.AppConfig.String("ViewsPath")
		if prefix == "" {
			prefix = "views/"
		}

		template, err = p2.FromFile(prefix + tmpl)
		if err != nil {
			panic(err)
		}
		mutex.Lock()
		templates[tmpl] = template
		mutex.Unlock()
	}

	var pCtx p2.Context
	if ctx == nil {
		pCtx = p2.Context{}
	} else {
		pCtx = p2.Context(ctx)
	}

	if xsrf, ok := beegoCtx.GetSecureCookie(beego.XSRFKEY, "_xsrf"); ok {
		pCtx["_xsrf"] = xsrf
	}

	// Only override "flash" if it hasn't already been set in Context
	if _, ok := ctx["flash"]; !ok {
		if ctx == nil {
			ctx = Context{}
		}
		ctx["flash"] = readFlash(beegoCtx)
	}

	err := template.ExecuteWriter(pCtx, beegoCtx.ResponseWriter)
	if err != nil {
		panic(err)
	}
}
Пример #2
0
func Pongo2() HandlerFunc {
	return func(c *Context) {
		c.Next()

		templateName, templateNameExists := c.Get("template")
		templateData, templateDataExists := c.Get("data")
		templateNameValue, isString := templateName.(string)

		if templateNameExists && templateDataExists && isString {
			template := pongo2.Must(pongo2.FromFile(templateNameValue))
			err := template.ExecuteWriter(getContext(templateData), c.Writer)
			if err != nil {
				http.Error(c.Writer, err.Error(), http.StatusInternalServerError)
			}
		}
	}
}