コード例 #1
0
ファイル: template.go プロジェクト: gophergala2016/source
// applyBody
func applyBody(t *template.Template, names, bodies []string) (*template.Template, error) {
	for i := 0; i < len(names); i++ {
		name, body := names[i], bodies[i]
		var tmpl *template.Template
		if t == nil {
			t = template.New(name)
		}
		if name == t.Name() {
			tmpl = t
		} else {
			tmpl = t.New(name)
		}
		if len(Template.Filters) > 0 {
			tmpl = applyFilters(tmpl, Template.Filters...)
		}
		if Template.Delims.isValid() {
			tmpl.Delims(Template.Delims.Get())
		}
		DebugPrintf("Parse as \"%s\"\n", name)
		_, err := tmpl.Parse(body)
		if err != nil {
			return nil, err
		}
	}
	return t, nil
}
コード例 #2
0
ファイル: console.go プロジェクト: mysll/flynet
func renderBaseHtml(handler Handler, base string, tmpl string, data map[string]interface{}) (err error) {
	var t *template.Template

	if base != "" {
		baseBytes, err := ioutil.ReadFile(tplPath + base)
		if err != nil {
			panic(err)
		}
		t, err = templates[tmpl].Clone()
		if err != nil {
			panic(err)
		}
		t, err = t.Parse(string(baseBytes))
		if err != nil {
			panic(err)
		}
	} else {
		t = templates[tmpl]
	}

	user, ok := currentUser(handler.Request)

	if ok {
		data["username"] = user.Username
		data["servers"] = master.app
	}

	err = t.Execute(handler.ResponseWriter, data)
	check(err)
	return
}
コード例 #3
0
ファイル: blog.go プロジェクト: joelgwebber/j15r.com
func InitBlog(tmpl *template.Template) (ArticleProvider, error) {
	var b = &blog{tmpl: tmpl}
	b.initArticleIndex()

	// Handlers.
	http.Handle("/blog/", b)

	// Special-cases ("/2011/", et al) to URLs from the old Blogger site.
	http.Handle("/2011/", b)
	http.Handle("/2010/", b)
	http.Handle("/2009/", b)
	http.Handle("/2007/", b)
	http.Handle("/2005/", b)
	http.Handle("/2004/", b)

	// Atom (old & new).
	http.HandleFunc("/feeds/posts/default", b.atomServer())
	http.HandleFunc("/blog/feed", b.atomServer())

	// Drafts.
	http.HandleFunc("/blog/drafts/", b.draftServer())

	// Calculate the reverse url map.
	for k, v := range originalUrls {
		reverseUrls[v] = k
	}

	_, err := tmpl.Parse(blogTemplate)
	if err != nil {
		return nil, err
	}

	return b, nil
}
コード例 #4
0
ファイル: template.go プロジェクト: husio/apps
func parseFiles(filenames ...string) (*template.Template, error) {
	if len(filenames) == 0 {
		// Not really a problem, but be consistent.
		return nil, fmt.Errorf("template: no files named in call to ParseFiles")
	}

	var t *template.Template
	for _, filename := range filenames {
		b, err := ioutil.ReadFile(filename)
		if err != nil {
			return nil, err
		}
		s := string(b)
		name := filepath.Base(filename)
		var tmpl *template.Template
		if t == nil {
			t = template.New(name).Funcs(baseFuncs)
		}
		if name == t.Name() {
			tmpl = t
		} else {
			tmpl = t.New(name)
		}
		_, err = tmpl.Parse(s)
		if err != nil {
			return nil, err
		}
	}
	return t, nil
}
コード例 #5
0
ファイル: templates.go プロジェクト: kjk/differ
func parseTemplates(filenames ...string) (*template.Template, error) {
	var t *template.Template
	for _, filename := range filenames {
		b, err := loadTemplate(filename)
		if err != nil {
			return nil, err
		}
		s := string(b)
		name := filepath.Base(filename)
		// First template becomes return value if not already defined,
		// and we use that one for subsequent New calls to associate
		// all the templates together. Also, if this file has the same name
		// as t, this file becomes the contents of t, so
		//  t, err := New(name).Funcs(xxx).ParseFiles(name)
		// works. Otherwise we create a new template associated with t.
		var tmpl *template.Template
		if t == nil {
			t = template.New(name)
		}
		if name == t.Name() {
			tmpl = t
		} else {
			tmpl = t.New(name)
		}
		_, err = tmpl.Parse(s)
		if err != nil {
			return nil, err
		}
	}
	return t, nil
}
コード例 #6
0
ファイル: template.go プロジェクト: shaoshing/mangotemplate
func parseTemplates(tpl *template.Template) (err error) {
	templatesToBeParsed := []string{tpl.Name()}

	for len(templatesToBeParsed) != 0 {
		name := templatesToBeParsed[0]
		templatesToBeParsed = templatesToBeParsed[1:]

		parsed := false
		for _, t := range tpl.Templates() {
			if tpl.Name() != name && t.Name() == name {
				parsed = true
				break
			}
		}

		if !parsed {
			content, err := readTemplate(name)
			if err != nil {
				return err
			}
			_, err = tpl.Parse(content)
			check(err)

			for _, matched := range templateKeyword.FindAllStringSubmatch(content, -1) {
				templatesToBeParsed = append(templatesToBeParsed, matched[1])
			}
		}
	}

	return
}
コード例 #7
0
func (t *BinTemplate) LoadDirectory(directory string) (*template.Template, error) {
	var tmpl *template.Template

	files, err := t.AssetDir(directory)
	if err != nil {
		return tmpl, err
	}

	for _, filePath := range files {
		contents, err := t.Asset(directory + "/" + filePath)
		if err != nil {
			return tmpl, err
		}

		name := filepath.Base(filePath)

		if tmpl == nil {
			tmpl = template.New(name)
		}

		if name != tmpl.Name() {
			tmpl = tmpl.New(name)
		}

		if _, err = tmpl.Parse(string(contents)); err != nil {
			return tmpl, err
		}
	}

	return tmpl, nil
}
コード例 #8
0
ファイル: filesystem.go プロジェクト: robdimsdale/garagepi
func LoadTemplates() (*template.Template, error) {
	// Below is taken from http://golang.org/src/html/template/template.go
	// because there is no way to get all the templates from the in-memory filesystem.
	// We would like to use e.g. ParseFiles but that is hard-coded
	// to use an actual filesystem; we cannot retarget it.
	var t *template.Template
	for _, filename := range filenames {
		s, err := templates.FSString(false, filename)
		if err != nil {
			return nil, err
		}
		name := filepath.Base(filename)
		// First template becomes return value if not already defined,
		// and we use that one for subsequent New calls to associate
		// all the templates together. Also, if this file has the same name
		// as t, this file becomes the contents of t, so
		//  t, err := New(name).Funcs(xxx).ParseFiles(name)
		// works. Otherwise we create a new template associated with t.
		var tmpl *template.Template
		if t == nil {
			t = template.New(name)
		}
		if name == t.Name() {
			tmpl = t
		} else {
			tmpl = t.New(name)
		}
		_, err = tmpl.Parse(s)
		if err != nil {
			return nil, err
		}
	}
	return t, nil
}
コード例 #9
0
ファイル: render.go プロジェクト: hobo-c/gin_sample
// parseFiles is the helper for the method and function. If the argument
// template is nil, it is created from the first file.
func parseBindataFiles(filenames ...string) (*template.Template, error) {
	var t *template.Template
	if len(filenames) == 0 {
		// Not really a problem, but be consistent.
		return nil, fmt.Errorf("html/template: no files named in call to ParseFiles")
	}
	for _, filename := range filenames {
		b, err := templates.Asset(filename)
		if err != nil {
			return nil, err
		}
		s := string(b)
		name := filepath.Base(filename)
		// First template becomes return value if not already defined,
		// and we use that one for subsequent New calls to associate
		// all the templates together. Also, if this file has the same name
		// as t, this file becomes the contents of t, so
		//  t, err := New(name).Funcs(xxx).ParseFiles(name)
		// works. Otherwise we create a new template associated with t.
		var tmpl *template.Template
		if t == nil {
			t = template.New(name)
		}
		if name == t.Name() {
			tmpl = t
		} else {
			tmpl = t.New(name)
		}
		_, err = tmpl.Parse(s)
		if err != nil {
			return nil, err
		}
	}
	return t, nil
}
コード例 #10
0
ファイル: tpl_demo1.go プロジェクト: aarzilli/tools
func templatesCompileDemo(w http.ResponseWriter, r *http.Request, m map[string]interface{}) {

	w.Header().Set("Content-Type", "text/html")

	funcMap := tt.FuncMap{
		"unescape": html.UnescapeString,
		"escape":   html.EscapeString,
	}

	var t_base *tt.Template
	var err error = nil

	// creating T0 - naming it - adding func map
	t_base = tt.Must(tt.New("str_T0_outmost").Funcs(funcMap).Parse(T0))
	loghttp.E(w, r, err, false)

	// adding the definition of T1 - introducing reference to T2 - undefined yet
	t_base, err = t_base.Parse(T1) // definitions must appear at top level - but not at the start
	loghttp.E(w, r, err, false)

	// create two clones
	// now both containing T0 and T1
	tc_1, err := t_base.Clone()
	loghttp.E(w, r, err, false)
	tc_2, err := t_base.Clone()
	loghttp.E(w, r, err, false)

	// adding different T2 definitions
	s_if := "{{if .}}{{.}}{{else}}no dyn data{{end}}"
	tc_1, err = tc_1.Parse("{{define `T2`}}T2-A  <br>--" + s_if + "--  {{end}}")
	loghttp.E(w, r, err, false)
	tc_2, err = tc_2.Parse("{{define `T2`}}T2-B  <br>--" + s_if + "--  {{end}}")
	loghttp.E(w, r, err, false)

	// writing both clones to the response writer
	err = tc_1.ExecuteTemplate(w, "str_T0_outmost", nil)
	loghttp.E(w, r, err, false)

	// second clone is written with dynamic data on two levels
	dyndata := map[string]string{"key1": "dyn val 1", "key2": "dyn val 2"}
	err = tc_2.ExecuteTemplate(w, "str_T0_outmost", dyndata)
	loghttp.E(w, r, err, false)

	// Note: it is important to pass the DOT
	//		 {{template "T1" .}}
	//		 {{template "T2" .key2 }}
	//						 ^
	// otherwise "dyndata" can not be accessed by the inner templates...

	// leaving T2 undefined => error
	tc_3, err := t_base.Clone()
	loghttp.E(w, r, err, false)
	err = tc_3.ExecuteTemplate(w, "str_T0_outmost", dyndata)
	// NOT logging the error:
	// loghttp.E(w, r, err, false)

}
コード例 #11
0
ファイル: template.go プロジェクト: yanap/monsti
// Parse the named template and add to the existing template structure.
//
// name is the name of the template (e.g. "blocks/sidebar").
// t is the existing template structure.
// root is the path to the templates.
//
// Returns false, nil if no template was found.
func parse(name string, t *template.Template, root string) (bool, error) {
	path := filepath.Join(root, name+".html")
	content, err := ioutil.ReadFile(path)
	if os.IsNotExist(err) {
		return false, nil
	} else if err != nil {
		return false, fmt.Errorf("Could not read template file: %v", err)
	}
	if _, err = t.Parse(string(content)); err != nil {
		return false, fmt.Errorf("Could not parse template file: %v", err)
	}
	return true, nil
}
コード例 #12
0
ファイル: settings.go プロジェクト: ancientHacker/susen.go
// parsePageTemplate takes an empty template, finds the template
// Page file associated with the teamplate's name, and parses
// that file's content into the template.
func parsePageTemplate(tmpl *template.Template) (*template.Template, error) {
	name := tmpl.Name()
	fp := filepath.Join(findTemplateDirectory(), name+templatePageSuffix)
	text, err := ioutil.ReadFile(fp)
	if err != nil {
		return nil, err
	}
	tmpl, err = tmpl.Parse(string(text))
	if err != nil {
		return nil, err
	}
	return tmpl, nil
}
コード例 #13
0
ファイル: test109.go プロジェクト: elivoa/gotapestry
func parseTemplate(key string, content string) error {
	// Old version uses filename as key, I make my own key. not
	// filepath.Base(filename) First template becomes return value if
	// not already defined, we use that one for subsequent New
	// calls to associate all the templates together. Also, if this
	// file has the same name as t, this file becomes the contents of
	// t, so t, err := New(name).Funcs(xxx).ParseFiles(name)
	// works. Otherwise we create a new template associated with t.

	fmt.Println("\n\n--------------------------------------------------------------------------------")
	fmt.Printf("[parse tempalte] parseTempalte(%s,<<%s>>);\n", key, content) //content) // REMOVE

	engine := Engine

	if engine.template == nil {
		engine.template = template.New(key)
	}

	var tmpl *template.Template
	// fmt.Println("0000000000000 > ", key, engine.template.Name())
	if key == engine.template.Name() {
		// fmt.Println(".... User old name, ", engine.template.Name())
		tmpl = engine.template
	} else {
		// fmt.Println(".... New name, ", key)
		tmpl = engine.template.New(key)
	}

	if true { // -------------------------- debug print templates.
		fmt.Println("\ndebug info { // templates loop ; tmpl.name is : ", tmpl.Name())
		for _, t := range engine.template.Templates() {
			fmt.Println("  ", t.Name())
		}
		fmt.Println("}")
	}

	// newt, e := tmpl.Clone()
	// if e != nil {
	// 	panic(e)
	// }
	// _, err := newt.Parse(content)
	_, err := tmpl.Parse(content)

	// fmt.Printf("[parse tempalte] End parseTempalte(%s, << ignored >>);\n", key) // REMOVE
	if err != nil {
		// fmt.Println("[ERROR] : \t", err) // REMOVE
		return err
	}
	engine.template = tmpl
	return nil
}
コード例 #14
0
ファイル: render.go プロジェクト: go-baa/baa
// parseFile ...
func parseFile(filename string) (*template.Template, error) {
	var t *template.Template
	b, err := ioutil.ReadFile(filename)
	if err != nil {
		return nil, err
	}
	s := string(b)
	name := filepath.Base(filename)
	t = template.New(name)
	_, err = t.Parse(s)
	if err != nil {
		return nil, err
	}
	return t, nil
}
コード例 #15
0
ファイル: view.go プロジェクト: pangudashu/foolgo
func parseTemplate(template *template.Template, file string) (t *template.Template, err error) { /*{{{*/
	data, _ := ioutil.ReadFile(file)

	t, err = template.Parse(string(data))
	if err != nil {
		return nil, err
	}

	reg := regexp.MustCompile(`{{\s{0,}template\s{0,}"(.*?)".*?}}`)
	match := reg.FindAllStringSubmatch(string(data), -1)
	for _, v := range match {
		if v == nil || v[1] == "" {
			continue
		}
		tlook := t.Lookup(v[1])
		if tlook != nil {
			continue
		}
		deep_file := ViewRoot + "/" + v[1] + ViewExt
		if deep_file == file {
			continue
		}

		t, err = parseTemplate(t, deep_file)

		if err != nil {
			return nil, err
		}
	}
	return t, nil
} /*}}}*/
コード例 #16
0
ファイル: tmpl.go プロジェクト: go-denji/pastecat
func loadTemplates() {
	for name, s := range templates {
		var t *template.Template
		if tmpl == nil {
			tmpl = template.New(name)
		}
		if name == tmpl.Name() {
			t = tmpl
		} else {
			t = tmpl.New(name)
		}
		if _, err := t.Parse(s); err != nil {
			panic("could not load templates")
		}
	}
}
コード例 #17
0
ファイル: base.go プロジェクト: Zxnui/go_web_demo
//为模板增加方法
func TemParseFiles(t *template.Template, filenames ...string) (*template.Template, error) {
	if len(filenames) == 0 {
		return nil, fmt.Errorf("html/template: no files named in call to ParseFiles")
	}
	for _, filename := range filenames {
		b, err := ioutil.ReadFile(filename)
		if err != nil {
			return nil, err
		}
		s := string(b)
		_, err = t.Parse(s)
		if err != nil {
			return nil, err
		}
	}
	return t, nil
}
コード例 #18
0
ファイル: session.go プロジェクト: sogko/gotcha
func (session *Session) render(asset string) error {
	asset = "assets/templates/" + asset

	var t *template.Template

	c, ok := session.Config.Cache["template:"+asset]
	if !ok {
		log.Trace("Loading asset: %s", asset)
		a, err := session.Config.AssetLoader(asset)
		log.Trace("Creating template: %s", asset)
		t = template.New(asset)
		t.Delims(session.Config.LeftDelim, session.Config.RightDelim)
		if err != nil || a == nil {
			log.Error("Failed loading template %s: %s", asset, err)
			return err
		}
		log.Trace("Parsing template: %s", asset)
		_, err = t.Parse(string(a))
		if err != nil {
			log.Error("Failed parsing template %s: %s", asset, err)
			return err
		}
		log.Trace("Template parsed successfully: %s", asset)
		session.Config.Cache["template:"+asset] = t
	} else {
		t = c.(*template.Template)
		log.Trace("Template loaded from cache: %s", asset)
	}

	var b bytes.Buffer
	err := t.Execute(&b, session.Stash)
	if err != nil {
		log.Error("Failed executing template %s: %s", asset, err)
		return err
	}

	_, err = session.Response.Write(b.Bytes())

	if err != nil {
		log.Error("Error writing output for template %s: %s", asset, err)
		return err
	}

	return nil
}
コード例 #19
0
ファイル: gotogether.go プロジェクト: CasualSuperman/goembed
// LoadTemplates loads named templates from resources.
// If the argument "t" is nil, it is created from the first resource.
func LoadTemplates(t *template.Template, filenames ...string) (*template.Template, error) {
	if err := Initialize(); err != nil {
		return nil, err
	}

	if len(filenames) == 0 {
		// Not really a problem, but be consistent.
		return nil, fmt.Errorf("no files named in call to LoadTemplates")
	}

	for _, filename := range filenames {
		rsc := Get(filename)
		if rsc == nil {
			return nil, fmt.Errorf("can't find %s", filename)
		}

		rdr, err := rsc.Open()
		if err != nil {
			return nil, fmt.Errorf("can't open %s - %s", filename, err)
		}
		data, err := ioutil.ReadAll(rdr)
		if err != nil {
			return nil, err
		}

		var tmpl *template.Template
		name := filepath.Base(filename)
		if t == nil {
			t = template.New(name)
		}
		if name == t.Name() {
			tmpl = t
		} else {
			tmpl = t.New(name)
		}
		_, err = tmpl.Parse(string(data))
		if err != nil {
			return nil, err
		}
	}
	return t, nil
}
コード例 #20
0
ファイル: template.go プロジェクト: gophergala2016/source
// parseFiles is the helper for the method and function. If the argument
// template is nil, it is created from the first file.
func parseFiles(t *template.Template, relativePath string, filenames ...string) (*template.Template, error) {
	if len(filenames) == 0 {
		// Not really a problem, but be consistent.
		return nil, fmt.Errorf("html/template: no files named in call to ParseFiles")
	}
	for _, filename := range filenames {
		b, err := ioutil.ReadFile(filename)
		if err != nil {
			return nil, err
		}
		s := string(b)

		name := templateName(relativePath, filename)
		// First template becomes return value if not already defined,
		// and we use that one for subsequent New calls to associate
		// all the templates together. Also, if this file has the same name
		// as t, this file becomes the contents of t, so
		//  t, err := New(name).Funcs(xxx).ParseFiles(name)
		// works. Otherwise we create a new template associated with t.
		var tmpl *template.Template
		if t == nil {
			t = template.New(name)
		}
		if name == t.Name() {
			tmpl = t
		} else {
			tmpl = t.New(name)
		}
		if len(Template.Filters) > 0 {
			tmpl = applyFilters(tmpl, Template.Filters...)
		}
		if Template.Delims.isValid() {
			tmpl.Delims(Template.Delims.Get())
		}
		DebugPrintf("Parse as \"%s\"\n", name)
		_, err = tmpl.Parse(s)
		if err != nil {
			return nil, err
		}
	}
	return t, nil
}
コード例 #21
0
ファイル: domainmux.go プロジェクト: sthapaun/ex
func parseTemplates(t *template.Template, templates ...string) (*template.Template, error) {
	if len(templates) == 0 {
		return nil, fmt.Errorf("No templates specified in call to ParseTemplates.")
	}
	name := "temporary.template.name"
	for _, tv := range templates {
		var tmpl *template.Template
		if t == nil {
			t = template.New(name)
		}
		tmpl = t

		_, err := tmpl.Parse(tv)
		if err != nil {
			return nil, err
		}
	}

	return t, nil
}
コード例 #22
0
ファイル: temple.go プロジェクト: captncraig/temple
func mapToTemplate(storedTemplates map[string]string) (*template.Template, error) {
	var t *template.Template
	for name, text := range storedTemplates {
		var tpl *template.Template
		if t == nil {
			tpl = template.New(name)
			t = tpl
		} else {
			tpl = t.New(name)
		}
		decoded, err := base64.StdEncoding.DecodeString(text)
		if err != nil {
			return nil, err
		}
		tpl, err = tpl.Parse(string(decoded))
		if err != nil {
			return nil, err
		}
	}
	return t, nil
}
コード例 #23
0
ファイル: http.go プロジェクト: studygolang/studygolang
func executeTpl(ctx echo.Context, tpl *template.Template, data map[string]interface{}) error {
	objLog := logic.GetLogger(ctx)

	// 如果没有定义css和js模板,则定义之
	if jsTpl := tpl.Lookup("js"); jsTpl == nil {
		tpl.Parse(`{{define "js"}}{{end}}`)
	}
	if jsTpl := tpl.Lookup("css"); jsTpl == nil {
		tpl.Parse(`{{define "css"}}{{end}}`)
	}

	// 当前用户信息
	curUser, ok := ctx.Get("user").(*model.Me)
	if ok {
		data["me"] = curUser
	} else {
		data["me"] = map[string]interface{}{}
	}

	// websocket主机
	if global.OnlineEnv() {
		data["wshost"] = config.ConfigFile.MustValue("global", "domain")
	} else {
		data["wshost"] = global.App.Host + ":" + global.App.Port
	}
	global.App.SetUptime()
	data["app"] = global.App

	data["online_users"] = map[string]int{"online": logic.Book.Len(), "maxonline": logic.MaxOnlineNum()}

	buf := new(bytes.Buffer)
	err := tpl.Execute(buf, data)
	if err != nil {
		objLog.Errorln("excute template error:", err)
		return err
	}

	return ctx.HTML(http.StatusOK, buf.String())
}
コード例 #24
0
ファイル: layouts.go プロジェクト: james4k/frontend
func (g *Group) load(filename string) error {
	front := make(map[string]interface{}, 4)
	content, err := fmatter.ReadFile(filename, front)
	if err != nil {
		return err
	}

	path := filename
	filename = filepath.Base(filename)
	ext := filepath.Ext(filename)
	name := filename[:len(filename)-len(ext)]
	_, ok := g.dict[name]
	if ok {
		return nil
	}

	var t *template.Template
	if g.tmpls == nil {
		t = template.New(name)
		g.tmpls = t
		t.Funcs(template.FuncMap{
			"content": undefinedContent,
		})
		t.Funcs(g.funcs)
	} else {
		t = g.tmpls.New(name)
	}

	_, err = t.Parse(string(content))
	if err != nil {
		// hrm.. how do we remove a template..?
		return err
	}

	parent, _ := front["layout"].(string)
	g.dict[name] = Entry{unexportedEntry{t}, name, path, parent}
	return nil
}
コード例 #25
0
func get(driver *Template, name string) *Template {

	var contents string
	var t *template.Template
	var err error

	pth := "resources/template/" + name + ".tmpl"
	partials := filepath.Join(filepath.Dir(pth), "partials", "_*.tmpl")

	contents, err = load(pth)
	if err != nil {
		return &Template{nil, err}
	}

	if driver != nil {
		t, err = driver.Clone()
		if err != nil {
			return &Template{nil, err}
		}

		_, err = t.Parse(contents)
		for _, name := range blocknames {
			if found := t.Lookup(name); found == nil {
				t.Parse("{{ define `" + name + "`}}{{ end }}")
			}
		}

		t.ParseGlob(partials)

	} else {
		t = template.New(name)
		if err != nil {
			return &Template{nil, err}
		}
		t, err = t.Funcs(funcMap).Parse(contents)
	}
	return &Template{t, err}
}
コード例 #26
0
ファイル: template.go プロジェクト: chrneumann/monsti
// Parse the named template and add to the existing template structure.
//
// name is the name of the template (e.g. "blocks/sidebar")
// t is the existing template structure.
// root is the path to monsti's template
// siteRoot is the path to the sites' overriden templates.
func parse(name string, t *template.Template, root string,
	siteRoot string) error {
	if len(siteRoot) > 0 {
		path := filepath.Join(siteRoot, name+".html")
		content, err := ioutil.ReadFile(path)
		if err == nil {
			_, err = t.Parse(string(content))
			if err != nil {
				return fmt.Errorf("Could not parse template: %v", err)
			}
			return nil
		}
	}
	path := filepath.Join(root, name+".html")
	content, err := ioutil.ReadFile(path)
	if err != nil {
		return fmt.Errorf("Could not load template: %v", err)
	}
	_, err = t.Parse(string(content))
	if err != nil {
		return fmt.Errorf("Could not parse template: %v", err)
	}
	return nil
}
コード例 #27
0
ファイル: resthtmlformater.go プロジェクト: extrame/goweb
func parseFileWithName(parent *template.Template, name string, filepath string) error {
	b, err := ioutil.ReadFile(filepath)
	if err != nil {
		return err
	}
	s := string(b)
	// First template becomes return value if not already defined,
	// and we use that one for subsequent New calls to associate
	// all the templates together. Also, if this file has the same name
	// as t, this file becomes the contents of t, so
	//  t, err := New(name).Funcs(xxx).ParseFiles(name)
	// works. Otherwise we create a new template associated with t.
	var tmpl *template.Template
	if name == parent.Name() || name == "" {
		tmpl = parent
	} else {
		tmpl = parent.New(name)
	}
	_, err = tmpl.Parse(s)
	if err != nil {
		return err
	}
	return nil
}
コード例 #28
0
ファイル: helpers.go プロジェクト: npat-efault/mandel
// parseEntries parses (as HTML templates) all bundle entries with
// names starting with the given prefix and ending with the given
// extension (suffix). Each template is given the name of the
// respective entry without the prefix. Returns the first template
// parsed. All other templates are associated with it. Panics on
// error.
func parseEntries(idx bundle.Index,
	pref, ext string) *template.Template {
	var tmpl *template.Template

	for _, e := range idx.Dir(pref) {
		if !strings.HasSuffix(e.Name, ext) {
			continue
		}
		b, err := e.Decode(0)
		if err != nil {
			panic("parseEntries: " +
				e.Name + ": " + err.Error())
		}
		s := string(b)
		name := e.Name[len(pref):]

		var t *template.Template
		if tmpl == nil {
			tmpl = template.New(name)
		}
		if name == tmpl.Name() {
			t = tmpl
		} else {
			t = tmpl.New(name)
		}
		_, err = t.Parse(s)
		if err != nil {
			panic("parseEntries: " +
				e.Name + ": " + err.Error())
		}
	}
	if tmpl == nil {
		panic("parseEntries: No entries to parse")
	}
	return tmpl
}
コード例 #29
0
ファイル: renderer.go プロジェクト: corneldamian/httpwaymid
func parseFiles(templateDir string, filenames ...string) (*template.Template, error) {
	if len(filenames) == 0 {
		return nil, fmt.Errorf("template: no files named in call to ParseFiles")
	}

	if templateDir[len(templateDir)-1] != '/' {
		templateDir = filepath.Clean(templateDir) + "/"
	}

	var t *template.Template

	for _, filename := range filenames {
		b, err := ioutil.ReadFile(filename)
		if err != nil {
			return nil, err
		}
		s := string(b)
		name := filename[len(templateDir):]

		var tmpl *template.Template
		if t == nil {
			t = template.New(name)
		}
		if name == t.Name() {
			tmpl = t
		} else {
			tmpl = t.New(name)
		}

		_, err = tmpl.Parse(s)
		if err != nil {
			return nil, err
		}
	}
	return t, nil
}
コード例 #30
0
// Parse the contents of the template files and create an html.Template
func Parse() (*template.Template, error) {

	var t *template.Template
	for name, contents := range allTemplates {
		var tmpl *template.Template

		if t == nil {
			t = template.New(name).Funcs(funcMap)
		}

		if name == t.Name() {
			tmpl = t
		} else {
			tmpl = t.New(name)
		}

		_, err := tmpl.Parse(contents)
		if err != nil {
			return t, err
		}
	}

	return t, nil
}