当前位置: 首页>>代码示例>>Golang>>正文


Golang pongo2.FromFile函数代码示例

本文整理汇总了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
}
开发者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


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