• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Golang pongo2.FromFile函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Golang中github.com/flosch/pongo2.FromFile函数的典型用法代码示例。如果您正苦于以下问题:Golang FromFile函数的具体用法?Golang FromFile怎么用?Golang FromFile使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了FromFile函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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
}
开发者ID:hyperboloide,项目名称:pdfgen,代码行数:30,代码来源:template.go


示例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)
}
开发者ID:walkr,项目名称:gower,代码行数:34,代码来源:gower.go


示例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)
}
开发者ID:rinti,项目名称:baggio,代码行数:55,代码来源:main.go


示例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
}
开发者ID:crackcomm,项目名称:renderer,代码行数:8,代码来源:pongo.go


示例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)
	}
}
开发者ID:jjjachyty,项目名称:ibookings,代码行数:34,代码来源:Schedule.go


示例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)
}
开发者ID:ngc224,项目名称:colle,代码行数:7,代码来源:data.go


示例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)
	}
}
开发者ID:alfonsodev,项目名称:golang-web-seed,代码行数:26,代码来源:main.go


示例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)
		}
	}
}
开发者ID:vodka-contrib,项目名称:pongor,代码行数:35,代码来源:pongo2_template_test.go


示例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
}
开发者ID:doddo,项目名称:templetation,代码行数:8,代码来源:machine.go


示例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
}
开发者ID:jgautheron,项目名称:gocha,代码行数:14,代码来源:changelog.go


示例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,
	}
}
开发者ID:stepan-perlov,项目名称:gin_pongo2,代码行数:8,代码来源:main.go


示例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)
}
开发者ID:ngc224,项目名称:colle,代码行数:9,代码来源:controller.go


示例13: main

func main() {
	kingpin.Parse()
	t := pongo2.Must(pongo2.FromFile(*templatePath))

	err := t.ExecuteWriter(getContext(), os.Stdout)
	if err != nil {
		panic(err)
	}
}
开发者ID:madedotcom,项目名称:pongo-blender,代码行数:9,代码来源:pongo-blender.go


示例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)
	}
}
开发者ID:yatuhata,项目名称:golang,代码行数:10,代码来源:app.go


示例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
}
开发者ID:vodka-contrib,项目名称:pongor,代码行数:10,代码来源:pongor.go


示例16: DashboardHandler

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)
		}
	}

}
开发者ID:alfonsodev,项目名称:golang-web-seed,代码行数:11,代码来源:main.go


示例17: index

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)
}
开发者ID:kawaken,项目名称:steward,代码行数:12,代码来源:web.go


示例18: BenchmarkExecuteComplexWithSandboxActive

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)
		}
	}
}
开发者ID:runner-mei,项目名称:pongo2,代码行数:13,代码来源:pongo2_template_test.go


示例19: Index

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")
	}
}
开发者ID:MasashiSalvador57f,项目名称:bookify,代码行数:13,代码来源:user.go


示例20: Pongo2

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
		}
	}
}
开发者ID:gocore,项目名称:echo-pongo2,代码行数:51,代码来源:pongo2.go



注:本文中的github.com/flosch/pongo2.FromFile函数示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Golang pongo2.FromString函数代码示例发布时间:2022-05-23
下一篇:
Golang pongo2.AsValue函数代码示例发布时间:2022-05-23
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap