Пример #1
0
func NewTemplate(root, path string) *Template {
	t := &Template{
		Url:     path,
		RootDir: filepath.Join(root, path),
	}

	// fi, err := ioutil.ReadDir(t.RootDir)
	// if err != nil {
	// 	log.Fatalf("failed to open template dir '%s'", t.RootDir)
	// }

	indexPath := filepath.Join(t.RootDir, "index.html")
	if !fileExists(indexPath) {
		log.Fatal("template index '%s' not found.")
	} else if tmpl, err := pongo2.FromFile(indexPath); err != nil {
		log.Fatal(err)
	} else {
		t.Index = tmpl
	}

	footerPath := filepath.Join(t.RootDir, "footer.html")
	if !fileExists(footerPath) {
		return t
	} else if tmpl, err := pongo2.FromFile(footerPath); err != nil {
		log.Fatal(err)
	} else {
		t.Footer = tmpl
	}
	return t
}
Пример #2
0
func renderTemplate(filepath string, data map[string]interface{}) []byte {

	var out string
	var err error
	var template pongo2.Template

	// Read the template from the disk every time
	if ServerConfig.Debug {
		newTemplate, err := pongo2.FromFile(filepath)
		if err != nil {
			panic(err)
		}
		template = *newTemplate

	} else {
		// Read the template and cache it
		cached, ok := templateCache[filepath]
		if ok == false {
			newTemplate, err := pongo2.FromFile(filepath)
			if err != nil {
				panic(err)
			}
			templateCache[filepath] = *newTemplate
			cached = *newTemplate
		}
		template = cached
	}

	out, err = template.Execute(data)
	if err != nil {
		panic(err)
	}
	return []byte(out)
}
Пример #3
0
func main() {
    public_html, err := exists("./public_html/")
    check(err)
    if !public_html {
      os.Mkdir("./public_html/", 0755)
      os.Mkdir("./public_html/blog/", 0755)
      os.Mkdir("./public_html/assets/", 0755)
      ioutil.WriteFile("./public_html/assets/styles.css", []byte(""), 0644)
    }

    archive := make([]map[string]string, 0)

    files, _ := ioutil.ReadDir("./blog/")
    for _, filename := range files {
        // Ignore drafts
        if strings.HasPrefix(filename.Name(), "draft") {
            continue
        }

        filecontent, err := ioutil.ReadFile("./blog/" + filename.Name())
        check(err)

        // Read the metadata
        r, _ := regexp.Compile("(?m)^Title: (.*)$")
        title := r.FindStringSubmatch(string(filecontent))[1]
        filecontent = []byte(r.ReplaceAllString(string(filecontent), ""))

        r, _ = regexp.Compile("(?m)^Published: (.*)$")
        published := r.FindStringSubmatch(string(filecontent))[1]
        filecontent = []byte(r.ReplaceAllString(string(filecontent), ""))

        tpl, err := pongo2.FromFile("detail.html")
        check(err)

        f, err := tpl.Execute(pongo2.Context{"title": title, "published": published, "content": string(blackfriday.MarkdownCommon(filecontent))})
        check(err)

        finalfilename := strings.TrimSuffix(filename.Name(), filepath.Ext(filename.Name()))
        ioutil.WriteFile("./public_html/blog/" + finalfilename + ".html", []byte(f), 0644)

        m := make(map[string]string)
        m["url"] = "./blog/" + finalfilename + ".html"
        m["title"] = title

        archive = append(archive, m)
    }

    tpl, err := pongo2.FromFile("index.html")
    check(err)

    f, err := tpl.Execute(pongo2.Context{"items": archive})
    check(err)

    ioutil.WriteFile("./public_html/index.html", []byte(f), 0644)
}
Пример #4
0
// FromFile - Creates a new template structure from file.
func FromFile(fname string) (t Template, err error) {
	template, err := pongo2.FromFile(fname)
	if err != nil {
		return
	}
	return &pongoTemplate{Template: template}, nil
}
Пример #5
0
// 	if err != nil {
// 		http.Error(w, err.Error(), http.StatusInternalServerError)
// 	}
// }
func (this *ScheduleController) My() {
	w := this.ResponseWriter
	r := this.Request
	r.ParseForm()
	user := r.FormValue("user")

	page := u.Page{PageSize: 10, ShowPages: 5}

	currentPage := r.FormValue("page")

	log.Println("当前页数", currentPage)
	page.CurrentPage, _ = strconv.Atoi(currentPage)
	page.InitSkipRecords()

	log.Println("过滤多少页", page.SkipRecords)
	log.Println("总页数", page.TotalPages)
	order := m.Order{RUser: user}
	page = order.GetRuserOrders(page)
	page.InitTotalPages()

	context := pongo2.Context{"orderlist": page.Data}

	var tplExample = pongo2.Must(pongo2.FromFile("views/Schedule.my.tpl"))

	err := tplExample.ExecuteWriter(context, w)
	if err != nil {
		log.Println(err)
		http.Error(w, err.Error(), http.StatusInternalServerError)
	}
}
Пример #6
0
func (dm *DataManager) WriteRssFile(filename string, pctx pongo2.Context) {
	tpl, _ := pongo2.FromFile("rss2.j2")
	pctx["lastBuildDate"] = time.Now().Format(time.RFC1123)
	context, _ := tpl.ExecuteBytes(pctx)
	ioutil.WriteFile(filename, context, 0644)
	dm.Logger.WithFields(SetUpdateLog("rss")).Info("write file " + filename)
}
Пример #7
0
func HomeHandler(rw http.ResponseWriter, r *http.Request) {
	session, _ := store.Get(r, cfg.SessionName)
	conf = &oauth2.Config{
		ClientID:     os.Getenv("GOOGLE_CLIENT_ID"),
		ClientSecret: os.Getenv("GOOGLE_CLIENT_SECRET"),
		RedirectURL:  os.Getenv("GOOGLE_CLIENT_REDIRECT"),
		Scopes: []string{
			"https://www.googleapis.com/auth/plus.login",
			"https://www.googleapis.com/auth/userinfo.email",
			"https://www.googleapis.com/auth/userinfo.profile",
		},
		Endpoint: google.Endpoint,
	}

	if session.Values["googleId"] != nil {
		http.Redirect(rw, r, "/dashboard", 301)
	}
	// Generate google signin url with xsrf token
	url := conf.AuthCodeURL(session.Values["xsrf"].(string))
	tmpl := pongo2.Must(pongo2.FromFile("./templates/home.html"))
	err := tmpl.ExecuteWriter(pongo2.Context{"GoogleAuthUrl": url}, rw)

	if err != nil {
		http.Error(rw, err.Error(), http.StatusInternalServerError)
	}
}
Пример #8
0
func TestTemplates(t *testing.T) {
	// Add a global to the default set
	pongo2.Globals["this_is_a_global_variable"] = "this is a global text"

	matches, err := filepath.Glob("./template_tests/*.tpl")
	if err != nil {
		t.Fatal(err)
	}
	for idx, match := range matches {
		t.Logf("[Template %3d] Testing '%s'", idx+1, match)
		tpl, err := pongo2.FromFile(match)
		if err != nil {
			t.Fatalf("Error on FromFile('%s'): %s", match, err.Error())
		}
		testFilename := fmt.Sprintf("%s.out", match)
		testOut, rerr := ioutil.ReadFile(testFilename)
		if rerr != nil {
			t.Fatalf("Error on ReadFile('%s'): %s", testFilename, rerr.Error())
		}
		tplOut, err := tpl.ExecuteBytes(tplContext)
		if err != nil {
			t.Fatalf("Error on Execute('%s'): %s", match, err.Error())
		}
		if bytes.Compare(testOut, tplOut) != 0 {
			t.Logf("Template (rendered) '%s': '%s'", match, tplOut)
			errFilename := filepath.Base(fmt.Sprintf("%s.error", match))
			err := ioutil.WriteFile(errFilename, []byte(tplOut), 0600)
			if err != nil {
				t.Fatalf(err.Error())
			}
			t.Logf("get a complete diff with command: 'diff -ya %s %s'", testFilename, errFilename)
			t.Errorf("Failed: test_out != tpl_out for %s", match)
		}
	}
}
Пример #9
0
func (m Machine) renderTemplate(templateName string) (string, error) {
	var tpl = pongo2.Must(pongo2.FromFile(path.Join("templates", templateName)))
	result, err := tpl.Execute(pongo2.Context{"machine": m})
	if err != nil {
		return "", err
	}
	return result, err
}
Пример #10
0
// getFilledTemplate returns the filled template as a slice of bytes.
// Initially wanted to use here the stdlib's text/template but ran into issues
// with the if instruction.
// The template looks quite ugly because of the blank lines left by the tags.
// https://code.djangoproject.com/ticket/2594 (WONTFIX)
// https://github.com/flosch/pongo2/issues/94
func getFilledTemplate(ctxt pongo2.Context, tplFile string) ([]byte, error) {
	t := pongo2.Must(pongo2.FromFile(tplFile))
	output, err := t.ExecuteBytes(ctxt)
	if err != nil {
		log.Fatal(err)
	}
	return output, nil
}
Пример #11
0
func (p PongoDebug) Instance(name string, data interface{}) render.Render {
	t := pongo2.Must(pongo2.FromFile(path.Join(p.Path, name)))
	return Pongo{
		Template: t,
		Name:     name,
		Data:     data,
	}
}
Пример #12
0
func (cntr Controller) NewFeed(c web.C, w http.ResponseWriter, r *http.Request) {
	tpl, err := pongo2.FromFile("rss2.j2")
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	items := cntr.GetPageFeedItem(1, c.URLParams["category"], cntr.UserConfig.Site.ItemDays, cntr.UserConfig.Site.PageNewItemCount)
	tpl.ExecuteWriter(pongo2.Context{"items": items}, w)
}
Пример #13
0
func main() {
	kingpin.Parse()
	t := pongo2.Must(pongo2.FromFile(*templatePath))

	err := t.ExecuteWriter(getContext(), os.Stdout)
	if err != nil {
		panic(err)
	}
}
Пример #14
0
func viewPage(c *gin.Context, p string, pc pongo2.Context) {
	tpl, err := pongo2.FromFile(p)
	if err != nil {
		c.String(500, "Internal Server Error: cannot found %s", p)
	}
	err = tpl.ExecuteWriter(pc, c.Writer)
	if err != nil {
		c.String(500, "Internal Server Error: cannot execute %s", p)
	}
}
Пример #15
0
func (r *Renderer) buildTemplatesCache(name string) (t *pongo2.Template, err error) {
	r.lock.Lock()
	defer r.lock.Unlock()
	t, err = pongo2.FromFile(filepath.Join(r.Directory, name))
	if err != nil {
		return
	}
	r.templates[name] = t
	return
}
Пример #16
0
func DashboardHandler(rw http.ResponseWriter, r *http.Request) {
	session, _ := store.Get(r, cfg.SessionName)
	tmpl := pongo2.Must(pongo2.FromFile("./templates/dash.html"))
	if session.Values["googleId"] != "" {
		err := tmpl.ExecuteWriter(pongo2.Context{"GoogleId": session.Values["googleId"]}, rw)
		if err != nil {
			panic(err)
		}
	}

}
Пример #17
0
func index(c web.C, w http.ResponseWriter, r *http.Request) {
	pongo2.DefaultLoader.SetBaseDir("templates")
	tpl, err := pongo2.FromFile("index.html")
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	page := &Page{Title: "外部連携"}

	integrations := conf.Integrations
	tpl.ExecuteWriter(pongo2.Context{"page": page, "integrations": integrations}, w)
}
Пример #18
0
func BenchmarkExecuteComplexWithSandboxActive(b *testing.B) {
	tpl, err := pongo2.FromFile("template_tests/complex.tpl")
	if err != nil {
		b.Fatal(err)
	}
	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		err = tpl.ExecuteWriterUnbuffered(tplContext, ioutil.Discard)
		if err != nil {
			b.Fatal(err)
		}
	}
}
Пример #19
0
func (ctr *UserController) Index(c *gin.Context) {
	tpl, err := pongo2.FromFile("templates/user/index.html")
	if err != nil {
		c.String(500, "can't load template")
	}
	err = tpl.ExecuteWriter(
		pongo2.Context{"hoge": "hogehoge"},
		c.Writer,
	)
	if err != nil {
		c.String(500, "can't write to template")
	}
}
Пример #20
0
func Pongo2() echo.MiddlewareFunc {
	return func(h echo.HandlerFunc) echo.HandlerFunc {
		return func(ctx *echo.Context) error {
			err := h(ctx)
			if err != nil {
				return err
			}
			templateName := ctx.Get("template")
			if templateName == nil {
				http.Error(
					ctx.Response().Writer(),
					"Template in Context not defined.",
					500)
			}
			var contentType, encoding string
			var isString bool
			ct := ctx.Get("ContentType")
			if ct == nil {
				contentType = ContentHTML
			} else {
				contentType, isString = ct.(string)
				if !isString {
					contentType = ContentHTML
				}
			}
			cs := ctx.Get("charset")
			if cs == nil {
				encoding = defaultCharset
			} else {
				encoding, isString = cs.(string)
				if !isString {
					encoding = defaultCharset
				}
			}
			newContentType := contentType + "; charset=" + encoding
			templateNameValue, isString := templateName.(string)
			if isString {
				templateData := ctx.Get("data")
				var template = pongo2.Must(pongo2.FromFile(path.Join("templates", templateNameValue)))
				ctx.Response().Header().Set(ContentType, newContentType)
				err = template.ExecuteWriter(
					getContext(templateData), ctx.Response().Writer())
				if err != nil {
					http.Error(
						ctx.Response().Writer(), err.Error(), 500)
				}
			}
			return nil
		}
	}
}
Пример #21
0
// Render template among with machine and config struct
func (m Machine) renderTemplate(template string, config Config) (string, error) {

	template = path.Join(config.TemplatePath, template)
	if _, err := os.Stat(template); err != nil {
		return "", errors.New("Template does not exist")
	}

	var tpl = pongo2.Must(pongo2.FromFile(template))
	result, err := tpl.Execute(pongo2.Context{"machine": m, "config": config})
	if err != nil {
		return "", err
	}
	return result, err
}
Пример #22
0
func (r *Renderer) getTemplate(name string) (t *pongo2.Template, err error) {
	if r.Reload {
		return pongo2.FromFile(filepath.Join(r.Directory, name))
	}
	r.lock.RLock()
	var ok bool
	if t, ok = r.templates[name]; !ok {
		r.lock.RUnlock()
		t, err = r.buildTemplatesCache(name)
	} else {
		r.lock.RUnlock()
	}
	return
}
Пример #23
0
func (p PongoProduction) Instance(name string, data interface{}) render.Render {
	var t *pongo2.Template
	if tmpl, ok := p.Templates[name]; ok {
		t = tmpl
	} else {
		tmpl := pongo2.Must(pongo2.FromFile(path.Join(p.Path, name)))
		p.Templates[name] = tmpl
		t = tmpl
	}
	return Pongo{
		Template: t,
		Name:     name,
		Data:     data,
	}
}
Пример #24
0
func (self *PongoTemplate) Load(key string) error {
	tplPath := fmt.Sprintf("%s/%s.pongo", self.GetTemplateDir(), key)

	if _, err := os.Stat(tplPath); err == nil {
		if tpl, err := pongo2.FromFile(tplPath); err == nil {
			self.template = tpl
			return nil
		} else {
			return err
		}
		return nil
	} else {
		return err
	}
}
Пример #25
0
func (p *Render) Render(w http.ResponseWriter, code int, data ...interface{}) error {
	file := "templates/" + data[0].(string)
	ctx := data[1].(pongo2.Context)
	var t *pongo2.Template

	if tmpl, ok := p.cache[file]; ok {
		t = tmpl
	} else {
		if options.Debug {
			tmpl, err := pongo2.FromFile(file)
			if err != nil {
				return err
			}
			t = tmpl
		} else {
			buff, err := server.Asset(file)
			if err == nil {
				tmpl, err := pongo2.FromString(string(buff))
				if err != nil {
					return err
				}
				t = tmpl
			} else {
				tmpl, err := pongo2.FromFile(file)
				if err != nil {
					return err
				}
				t = tmpl
			}

		}
		p.cache[file] = t
	}
	writeHeader(w, code, "text/html")
	return t.ExecuteWriter(ctx, w)
}
Пример #26
0
func BenchmarkParallelExecuteComplexWithSandboxActive(b *testing.B) {
	tpl, err := pongo2.FromFile("template_tests/complex.tpl")
	if err != nil {
		b.Fatal(err)
	}
	b.ResetTimer()
	b.RunParallel(func(pb *testing.PB) {
		for pb.Next() {
			err := tpl.ExecuteWriterUnbuffered(tplContext, ioutil.Discard)
			if err != nil {
				b.Fatal(err)
			}
		}
	})
}
Пример #27
0
// Renders a template
func (t *Templating) Render(context Context, name string) {
	var filename = fmt.Sprintf("%s/%s", t.GetViewsDirectory(), name)

	if _, err := os.Stat(filename); err != nil {
		if os.IsNotExist(err) {
			log.Printf("View '%s' does not exists", filename)
			os.Exit(1)
		}
	}

	var template = pongo2.Must(pongo2.FromFile(filename))
	template.ExecuteWriter(pongo2.Context{
		"request":  context.GetRequest(),
		"response": context.GetResponse(),
	}, context.GetResponse())
}
Пример #28
0
func handleHelpPage(res http.ResponseWriter, r *http.Request) {
	content, err := ioutil.ReadFile("frontend/help.md")
	if err != nil {
		log.WithFields(logrus.Fields{
			"error": fmt.Sprintf("%v", err),
		}).Error("HelpText Load")
		http.Error(res, "An unknown error occured.", http.StatusInternalServerError)
		return
	}

	template := pongo2.Must(pongo2.FromFile("frontend/help.html"))
	ctx := getBasicContext(res, r)
	ctx["helptext"] = string(content)

	template.ExecuteWriter(ctx, res)
}
Пример #29
0
func Pongo2() HandlerFunc {
	return func(c *Context) {
		c.Next()

		templateName, templateNameError := c.Get("template")
		templateNameValue, isString := templateName.(string)

		if templateNameError == nil && isString {
			templateData, templateDataError := c.Get("data")
			var template = pongo2.Must(pongo2.FromFile(templateNameValue))
			err := template.ExecuteWriter(getContext(templateData, templateDataError), c.Writer)
			if err != nil {
				http.Error(c.Writer, err.Error(), http.StatusInternalServerError)
			}
		}
	}
}
Пример #30
0
// Instance should return a new Pongo2Render struct per request and prepare
// the template by either loading it from disk or using pongo2's cache.
func (p Pongo2Render) Instance(name string, data interface{}) render.Render {
	var template *pongo2.Template
	filename := path.Join(p.Options.TemplateDir, name)

	// always read template files from disk if in debug mode, use cache otherwise.
	if gin.Mode() == "debug" {
		template = pongo2.Must(pongo2.FromFile(filename))
	} else {
		template = pongo2.Must(pongo2.FromCache(filename))
	}

	return Pongo2Render{
		Template: template,
		Context:  data.(pongo2.Context),
		Options:  p.Options,
	}
}