示例#1
0
func (s *TestSuite) TestMisc(c *C) {
	// Must
	// TODO: Add better error message (see issue #18)
	c.Check(
		func() { pongo2.Must(testSuite2.FromFile("template_tests/inheritance/base2.tpl")) },
		PanicMatches,
		`\[Error \(where: fromfile\) in .*template_tests/inheritance/doesnotexist.tpl | Line 1 Col 12 near 'doesnotexist.tpl'\] open .*template_tests/inheritance/doesnotexist.tpl: no such file or directory`,
	)

	// Context
	c.Check(parseTemplateFn("", pongo2.Context{"'illegal": nil}), PanicMatches, ".*not a valid identifier.*")

	// Registers
	c.Check(func() { pongo2.RegisterFilter("escape", nil) }, PanicMatches, ".*is already registered.*")
	c.Check(func() { pongo2.RegisterTag("for", nil) }, PanicMatches, ".*is already registered.*")

	// ApplyFilter
	v, err := pongo2.ApplyFilter("title", pongo2.AsValue("this is a title"), nil)
	if err != nil {
		c.Fatal(err)
	}
	c.Check(v.String(), Equals, "This Is A Title")
	c.Check(func() {
		_, err := pongo2.ApplyFilter("doesnotexist", nil, nil)
		if err != nil {
			panic(err)
		}
	}, PanicMatches, `\[Error \(where: applyfilter\)\] Filter with name 'doesnotexist' not found.`)
}
示例#2
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)
	}
}
示例#3
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)
	}
}
示例#4
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,
	}
}
示例#5
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
}
示例#6
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,
	}
}
示例#7
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
}
示例#8
0
func (p Pongo2Common) Instance(name string, data interface{}) render.Render {
	tpl := pongo2.Must(pongo2.FromCache(path.Join(p.BasePath, name)))

	return &Pongo2{
		Template: tpl,
		Name:     name,
		Data:     data,
	}
}
示例#9
0
func main() {
	kingpin.Parse()
	t := pongo2.Must(pongo2.FromFile(*templatePath))

	err := t.ExecuteWriter(getContext(), os.Stdout)
	if err != nil {
		panic(err)
	}
}
示例#10
0
func handleViewer(res http.ResponseWriter, r *http.Request) {
	vars := mux.Vars(r)

	tplData, _ := Asset("viewer.html")
	tpl := pongo2.Must(pongo2.FromString(string(tplData)))
	tpl.ExecuteWriter(pongo2.Context{
		"ipfs_hash": vars["ipfs_hash"],
		"branding":  cfg.Branding,
	}, res)
}
示例#11
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)
		}
	}

}
示例#12
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
		}
	}
}
示例#13
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
}
示例#14
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,
	}
}
示例#15
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)
}
示例#16
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())
}
示例#17
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.FromCache(templateNameValue))
			err := template.ExecuteWriter(getContext(templateData, templateDataError), c.Writer)
			if err != nil {
				http.Error(c.Writer, err.Error(), http.StatusInternalServerError)
			}
		}
	}
}
示例#18
0
文件: copter.go 项目: plirr/copter
func (copter *Copter) compileTemplates() {
	dir := copter.options.Directory

	filepath.Walk(dir, func(path string, info os.FileInfo, err error) error {
		rel, err := filepath.Rel(dir, path)
		if err != nil {
			return err
		}

		ext := filepath.Ext(path)

		for _, extension := range copter.options.Extensions {
			if ext == extension {
				name := (rel[0 : len(rel)-len(ext)])
				pongo2.Must(copter.Set.FromCache(filepath.ToSlash(name) + ext))
				break
			}
		}

		return nil
	})
}
示例#19
0
文件: runner.go 项目: cfpb/rhobot
// NewPongo2ReportRunnerFromString constructor with template string
func NewPongo2ReportRunnerFromString(TemplateString string) *Pongo2ReportRunner {
	var template = pongo2.Must(pongo2.FromString(TemplateString))
	return &Pongo2ReportRunner{
		Template: *template,
	}
}
示例#20
0
文件: runner.go 项目: cfpb/rhobot
// NewPongo2ReportRunnerFromFile constructor with template file
func NewPongo2ReportRunnerFromFile(TemplateFilePath string) *Pongo2ReportRunner {
	var template = pongo2.Must(pongo2.FromFile(TemplateFilePath))
	return &Pongo2ReportRunner{
		Template: *template,
	}
}
示例#21
0
文件: web.go 项目: cubeee/go-sig
type NullWriter int

func (NullWriter) Write([]byte) (int, error) {
	return 0, nil
}

type SignatureRequest struct {
	hash      string
	generator generators.BaseGenerator
}

var (
	imageRoot      = "images"
	publicPath     = "public/"
	updateInterval = 10.0
	indexTemplate  = pongo2.Must(pongo2.FromFile("templates/index.tpl"))
)

func init() {
	runtime.GOMAXPROCS(runtime.NumCPU())
}

func createAndSaveSignature(writer http.ResponseWriter, req util.SignatureRequest, generator generators.BaseGenerator) error {
	// Create the signature image
	sig, err := generator.CreateSignature(req.Req)
	if err != nil {
		return err
	}

	// note: queue saving if it causes performance issues?
	// Save the image to disk with the given hash as the file name
示例#22
0
	"net/http"
	"net/url"

	"github.com/flosch/pongo2"
	"github.com/go-errors/errors"
	"github.com/google/go-github/github"
	"github.com/gorilla/context"
	"github.com/samertm/githubstreaks/conf"
	"github.com/samertm/githubstreaks/debug"
	"github.com/zenazn/goji"
	"github.com/zenazn/goji/web"
	"golang.org/x/oauth2"
	githuboauth "golang.org/x/oauth2/github"
)

var _ = pongo2.Must(pongo2.FromFile("templates/base.html"))

var errorTemplate = pongo2.Must(pongo2.FromFile("templates/error.html"))

type errorTemplateVars struct {
	Message string
	Code    int
}

// baseContext is the context that is fed into every template. Keep in
// alphabetical order: abcdefghijklmnopqrstuvwxyz.
var baseContext = pongo2.Context{
	"AbsoluteURL":        AbsoluteURL,
	"CommitGroups":       CommitGroups,
	"CommitMessageTitle": CommitMessageTitle,
	"GetGroupUsers": func(g Group) []User {
示例#23
0
func handlerRepositoryView(res http.ResponseWriter, r *http.Request) {
	sess, _ := sessionStore.Get(r, "GoBuilderSession")

	params := mux.Vars(r)
	branch := r.FormValue("branch")
	if branch == "" {
		branch = "master"
	}

	buildStatus, err := redisClient.Get(fmt.Sprintf("project::%s::build-status", params["repo"]))
	if err != nil || buildStatus == nil {
		log.WithFields(logrus.Fields{
			"error": fmt.Sprintf("%v", err),
			"repo":  params["repo"],
		}).Warn("AWS S3 Get Error")

		sess.AddFlash(flashContext{
			"error": "Your build is not yet known to us...",
			"value": params["repo"],
		}, "context")
		sess.Save(r, res)
		http.Redirect(res, r, "/", http.StatusFound)
		return
	}

	readmeContent, err := s3Bucket.Get(fmt.Sprintf("%s/%s_README.md", params["repo"], branch))
	if err != nil {
		readmeContent = []byte("Project provided no README.md file.")
	}

	buildDurationRaw, err := redisClient.Get(fmt.Sprintf("project::%s::build-duration", params["repo"]))
	if err != nil || len(buildDurationRaw) == 0 {
		buildDurationRaw = []byte("0")
	}
	buildDuration, err := strconv.Atoi(string(buildDurationRaw))
	if err != nil {
		buildDuration = 0
	}

	signature, err := redisClient.Get(fmt.Sprintf("project::%s::signatures::%s", params["repo"], branch))
	if err != nil {
		signature = []byte("")
	}

	buildDB := builddb.BuildDB{}
	hasBuilds := false

	file, err := getBuildDBWithFallback(params["repo"])
	if err != nil {
		buildDB["master"] = builddb.Branch{}
		hasBuilds = false
	} else {
		err = json.Unmarshal(file, &buildDB)
		if err != nil {
			log.WithFields(logrus.Fields{
				"error": fmt.Sprintf("%v", err),
			}).Error("AWS DB Unmarshal Error")

			sess.AddFlash("Your build is not yet known to us...", "alert_error")
			sess.Save(r, res)
			http.Redirect(res, r, "/", http.StatusFound)
			return
		}
		hasBuilds = true
	}

	logs, err := redisClient.ZRevRange(fmt.Sprintf("project::%s::logs", params["repo"]), 0, 10, false)
	if err != nil {
		logs = []string{}
		log.WithFields(logrus.Fields{
			"repo": params["repo"],
			"err":  err,
		}).Error("Unable to load last logs")
	}
	logMetas := []*buildjob.BuildLog{}
	for _, v := range logs {
		if l, err := buildjob.LogFromString(v); err == nil {
			logMetas = append(logMetas, l)
		} else {
			// TODO: Remove me. I'm only here for migration purposes!
			logMetas = append(logMetas, &buildjob.BuildLog{
				ID: v,
			})
		}
	}

	abortReason, _ := redisClient.Get(fmt.Sprintf("project::%s::abort", params["repo"]))

	template := pongo2.Must(pongo2.FromFile("frontend/repository.html"))
	branches := []builddb.BranchSortEntry{}
	for k, v := range buildDB {
		branches = append(branches, builddb.BranchSortEntry{Branch: k, BuildDate: v.BuildDate})
	}
	sort.Sort(sort.Reverse(builddb.BranchSortEntryByBuildDate(branches)))

	ctx := getBasicContext(res, r)
	ctx["branch"] = branch
	ctx["branches"] = branches
	ctx["repo"] = params["repo"]
	ctx["mybranch"] = buildDB[branch]
	ctx["buildStatus"] = string(buildStatus)
	ctx["readme"] = string(readmeContent)
	ctx["hasbuilds"] = hasBuilds
	ctx["buildDuration"] = buildDuration
	ctx["signature"] = string(signature)
	ctx["logs"] = logMetas
	ctx["abort"] = string(abortReason)

	template.ExecuteWriter(ctx, res)
}
示例#24
0
文件: handlers.go 项目: slok/monf
func init() {
	// Load varialbes with the settings loaded
	templatesPrefix = filepath.Join(viper.GetString(configuration.TemplatesPath), "panel")
	tplRoot = pongo2.Must(pongo2.FromFile(filepath.Join(templatesPrefix, "root.html")))
}
示例#25
0
package main

import (
	"encoding/json"
	"fmt"
	"github.com/flosch/pongo2"
	"github.com/gorilla/mux"
	"net/http"
	"strconv"
)

var tpl = pongo2.Must(pongo2.FromFile("views/home.html"))

func (repo *Repo) Home(w http.ResponseWriter, r *http.Request) {
	err := tpl.ExecuteWriter(pongo2.Context{"query": r.FormValue("query")}, w)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
	}
}

var tplItem = pongo2.Must(pongo2.FromFile("views/item.html"))

func (repo *Repo) Item(w http.ResponseWriter, r *http.Request) {
	err := tplItem.ExecuteWriter(pongo2.Context{"Items": r.FormValue("items")}, w)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
	}
}

func (repo *Repo) Index(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintln(w, "Welcome to my go api!")
示例#26
0
func handleFrontPage(res http.ResponseWriter, r *http.Request) {
	template := pongo2.Must(pongo2.FromFile("frontend/newbuild.html"))
	template.ExecuteWriter(getNewBuildContext(res, r), res)
}
示例#27
0
func handleImprint(res http.ResponseWriter, r *http.Request) {
	template := pongo2.Must(pongo2.FromFile("frontend/imprint.html"))
	template.ExecuteWriter(getBasicContext(res, r), res)
}
示例#28
0
文件: util.go 项目: cubeee/go-sig
	"github.com/golang/freetype/truetype"
	"github.com/zenazn/goji/web"
	"image"
	"io"
	"io/ioutil"
	"net/http"
	"net/url"
	"regexp"
	"strconv"
	"strings"
)

var (
	hasher         = md5.New()
	UsernameRegex  = regexp.MustCompile("^_?[a-zA-Z0-9-_+]+$")
	resultTemplate = pongo2.Must(pongo2.FromFile("templates/result.tpl"))
	AES_KEY        = []byte{}
)

type GoalType int

const (
	GoalLevel GoalType = iota
	GoalXP
)

type Signature struct {
	Username string
	Image    image.Image
}
示例#29
0
文件: main.go 项目: samertm/play
package main

import (
	"fmt"

	"github.com/flosch/pongo2"
)

var baseTemplate = pongo2.Must(pongo2.FromFile("base.html"))

// Compile the template at application start (for performance reasons)
var indexTemplate = pongo2.Must(pongo2.FromFile("index.html"))

type User struct {
	Login  string
	Email  string
	Groups []Group
}

type Group struct {
	ID int
}

func main() {
	// Execute the template
	renderedTemplate, err := indexTemplate.Execute(pongo2.Context{
		"user": User{Login: "******"},
		"sayhi": func(u User) (string, string) {
			return "Hello, " + u.Login, "yo"
		},
	})
示例#30
0
文件: main.go 项目: irth/blag
// LoadTheme loads pongo2 templates for both pages and posts.
// It will try to load templates from themeDir/page.html and
// themeDir/post.html, and it will panic if that will not succeed.
func LoadTheme(themeDir string) Theme {
	t := Theme{}
	t.Page = pongo2.Must(pongo2.FromFile(path.Join(themeDir, "templates", "page.html")))
	t.Post = pongo2.Must(pongo2.FromFile(path.Join(themeDir, "templates", "post.html")))
	return t
}