本文整理汇总了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
}
示例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
}
示例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
}
示例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
}
示例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
}
示例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
}
示例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
}
示例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
}
示例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
}
示例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)
}
示例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
}
示例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
}
示例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
}
示例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
}
示例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
} /*}}}*/