本文整理匯總了Golang中github.com/flosch/pongo2.FromFile函數的典型用法代碼示例。如果您正苦於以下問題:Golang FromFile函數的具體用法?Golang FromFile怎麽用?Golang FromFile使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。
在下文中一共展示了FromFile函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。
示例1: NewTemplate
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: renderTemplate
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: main
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: FromFile
// 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: My
// 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: WriteRssFile
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: HomeHandler
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: TestTemplates
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: renderTemplate
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: getFilledTemplate
// 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: Instance
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: NewFeed
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: main
func main() {
kingpin.Parse()
t := pongo2.Must(pongo2.FromFile(*templatePath))
err := t.ExecuteWriter(getContext(), os.Stdout)
if err != nil {
panic(err)
}
}
示例14: viewPage
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: buildTemplatesCache
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
}