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


Golang Template.Parse方法代码示例

本文整理汇总了Golang中html/template.Template.Parse方法的典型用法代码示例。如果您正苦于以下问题:Golang Template.Parse方法的具体用法?Golang Template.Parse怎么用?Golang Template.Parse使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在html/template.Template的用法示例。


在下文中一共展示了Template.Parse方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。

示例1: applyBody

// 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
}
开发者ID:gophergala2016,项目名称:source,代码行数:27,代码来源:template.go

示例2: renderBaseHtml

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
}
开发者ID:mysll,项目名称:flynet,代码行数:31,代码来源:console.go

示例3: InitBlog

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
}
开发者ID:joelgwebber,项目名称:j15r.com,代码行数:34,代码来源:blog.go

示例4: parseFiles

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
}
开发者ID:husio,项目名称:apps,代码行数:30,代码来源:template.go

示例5: parseTemplates

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
}
开发者ID:kjk,项目名称:differ,代码行数:31,代码来源:templates.go

示例6: parseTemplates

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
}
开发者ID:shaoshing,项目名称:mangotemplate,代码行数:31,代码来源:template.go

示例7: LoadDirectory

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
}
开发者ID:itsjamie,项目名称:go-bindata-templates,代码行数:31,代码来源:template.go

示例8: LoadTemplates

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
}
开发者ID:robdimsdale,项目名称:garagepi,代码行数:34,代码来源:filesystem.go

示例9: parseBindataFiles

// 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
}
开发者ID:hobo-c,项目名称:gin_sample,代码行数:37,代码来源:render.go

示例10: templatesCompileDemo

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)

}
开发者ID:aarzilli,项目名称:tools,代码行数:57,代码来源:tpl_demo1.go

示例11: parse

// 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
}
开发者ID:yanap,项目名称:monsti,代码行数:20,代码来源:template.go

示例12: parsePageTemplate

// 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
}
开发者ID:ancientHacker,项目名称:susen.go,代码行数:16,代码来源:settings.go

示例13: parseTemplate

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

示例14: parseFile

// 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
}
开发者ID:go-baa,项目名称:baa,代码行数:16,代码来源:render.go

示例15: parseTemplate

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
} /*}}}*/
开发者ID:pangudashu,项目名称:foolgo,代码行数:31,代码来源:view.go


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