// 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 }
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 }
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 }
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 }
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 }
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 }
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 }
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 }
// 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 }
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) }
// 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 }
// 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 }
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 }
// 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 }
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 } /*}}}*/
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") } } }
//为模板增加方法 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 }
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 }
// 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 }
// 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 }
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 }
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 }
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()) }
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 }
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} }
// 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 }
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 }
// 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 }
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 }
// 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 }