Exemplo n.º 1
0
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
}
Exemplo n.º 2
0
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
}
Exemplo n.º 3
0
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
}
Exemplo n.º 4
0
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
}
Exemplo n.º 5
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
}
Exemplo n.º 6
0
func buildTemplate(dir string, funcMap template.FuncMap) (*template.Template, error) {
	var t *template.Template
	return t, filepath.Walk(dir, func(path string, info os.FileInfo, err error) error {
		if !info.IsDir() {
			filetext, err := ioutil.ReadFile(path)
			if err != nil {
				return err
			}
			text := string(filetext)
			name := path[len(dir)+1:]
			name = strings.Replace(name, `\`, `/`, -1)

			var tmpl *template.Template
			if t == nil {
				t = template.New(name)
			}
			if name == t.Name() {
				tmpl = t
			} else {
				tmpl = t.New(name)
			}
			_, err = tmpl.Funcs(funcMap).Parse(text)
			if err != nil {
				return err
			}
		}
		return nil
	})
}
Exemplo n.º 7
0
func parseFiles(filenames ...string) (*template.Template, error) {
	var t *template.Template = nil
	var err error = nil

	if len(filenames) == 0 {
		return nil, fmt.Errorf("html/template: no files named in call to ParseFiles")
	}

	sort.Strings(filenames)

	for _, filename := range filenames {
		if t == nil {
			t = template.New(filename)
		}
		if filename != t.Name() {
			t = t.New(filename)
		}
		_, err = t.Funcs(funcMap).Parse(templates[filename])

		// anyone template syntax error throw panic
		if err != nil {
			panic(err)
		}
	}
	return t, err
}
Exemplo n.º 8
0
// 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
}
Exemplo n.º 9
0
func mkHttpHandler(h Handler, tpl *template.Template) http.HandlerFunc {
	return func(rw http.ResponseWriter, req *http.Request) {
		sess, err := getSess(req)
		if err != nil {
			req.Cookies()
			log.Printf("Error while getting session: %s", err)
			rw.Write([]byte("Unable to create a session. Try reloading the page or delete the cookies for this site."))
		}

		user := userFromSess(sess)
		outdata, user := h(user, sess, req)
		mail := ""
		if user != nil {
			mail = user.Email()
		}

		if err := sess.Save(req, rw); err != nil {
			log.Printf("Error while saving session: %s", err)
		}

		if err := tpl.Execute(rw, &tpldata{mail, outdata}); err != nil {
			log.Printf("Error executing template %s: %s", tpl.Name(), err)
		}
	}
}
Exemplo n.º 10
0
// 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
}
Exemplo n.º 11
0
func ShortcodeRender(tmpl *template.Template, data *ShortcodeWithPage) string {
	buffer := new(bytes.Buffer)
	err := tmpl.Execute(buffer, data)
	if err != nil {
		fmt.Println("error processing shortcode", tmpl.Name(), "\n ERR:", err)
	}
	return buffer.String()
}
Exemplo n.º 12
0
func tplHandler(t *template.Template) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		log.Println("Handling", r.URL, "with template", t.Name())
		if err := t.Execute(w, nil); err != nil {
			log.Println(err)
			http.Error(w, err.Error(), http.StatusInternalServerError)
		}
	})
}
Exemplo n.º 13
0
// returns "" on error
func templateToString(t *template.Template, data interface{}) string {
	var buf bytes.Buffer
	err := t.Execute(&buf, data)
	if err != nil {
		logger.Errorf("Failed to execute template '%s', error: %s", t.Name(), err.Error())
		return ""
	}
	return string(buf.Bytes())
}
Exemplo n.º 14
0
// Render a named template name to the HTTP channel
func renderTemplate(w io.Writer, tmpl template.Template, context interface{}) {
	log.Printf("Rendering %s", tmpl.Name())
	err := tmpl.ExecuteTemplate(w, "base.html", context)
	if err != nil {
		log.Printf("ERROR: %s", err)
		w.Write([]byte("Unable to render"))
		return
	}
}
Exemplo n.º 15
0
func renderShortcodeWithPage(tmpl *template.Template, data *ShortcodeWithPage) string {
	buffer := bp.GetBuffer()
	defer bp.PutBuffer(buffer)

	err := tmpl.Execute(buffer, data)
	if err != nil {
		jww.ERROR.Println("error processing shortcode", tmpl.Name(), "\n ERR:", err)
		jww.WARN.Println(data)
	}
	return buffer.String()
}
Exemplo n.º 16
0
func debugPrintLoadTemplate(tmpl *template.Template) {
	if IsDebugging() {
		var buf bytes.Buffer
		for _, tmpl := range tmpl.Templates() {
			buf.WriteString("\t- ")
			buf.WriteString(tmpl.Name())
			buf.WriteString("\n")
		}
		debugPrint("Loaded HTML Templates (%d): \n%s\n", len(tmpl.Templates()), buf.String())
	}
}
Exemplo n.º 17
0
// 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
}
Exemplo n.º 18
0
func printTemplate(tpl *template.Template, max, level int) {
	if level > max {
		return
	}
	log.Printf("Printing template: %v @ %v", tpl.Name(), level)
	for i, j := range tpl.Templates() {
		log.Printf("TEMPLATE: %v=%v", i, j.Name())
	}

	for _, j := range tpl.Templates() {
		printTemplate(j, max, level+1)
	}
}
Exemplo n.º 19
0
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
}
Exemplo n.º 20
0
func renderShortcodeWithPage(tmpl *template.Template, data *ShortcodeWithPage) string {
	buffer := bp.GetBuffer()
	defer bp.PutBuffer(buffer)

	// TODO(bep) Refactor/rename this lock strategy
	isInnerShortcodeCache.Lock()
	defer isInnerShortcodeCache.Unlock()
	err := tmpl.Execute(buffer, data)
	if err != nil {
		jww.ERROR.Println("error processing shortcode", tmpl.Name(), "\n ERR:", err)
		jww.WARN.Println(data)
	}
	return buffer.String()
}
Exemplo n.º 21
0
// to avoid potential costly look-aheads for closing tags we look inside the template itself
// we could change the syntax to self-closing tags, but that would make users cry
// the value found is cached
func isInnerShortcode(t *template.Template) bool {
	isInnerShortcodeCache.RLock()
	m, ok := isInnerShortcodeCache.m[t.Name()]
	isInnerShortcodeCache.RUnlock()

	if ok {
		return m
	}

	isInnerShortcodeCache.Lock()
	defer isInnerShortcodeCache.Unlock()
	match, _ := regexp.MatchString("{{.*?\\.Inner.*?}}", t.Tree.Root.String())
	isInnerShortcodeCache.m[t.Name()] = match

	return match
}
Exemplo n.º 22
0
func renderTemplate(w http.ResponseWriter, tmpl *template.Template, data interface{}) {
	err := tmpl.Execute(w, data)
	if err == nil {
		return
	}

	switch err := err.(type) {
	case *template.Error:
		// An ExecError guarantees that Execute has not written to the underlying reader.
		log.Printf("Error rendering template %s: %s", tmpl.Name(), err)

		// TODO(ericchiang): replace with better internal server error.
		http.Error(w, "Internal server error", http.StatusInternalServerError)
	default:
		// An error with the underlying write, such as the connection being
		// dropped. Ignore for now.
	}
}
Exemplo n.º 23
0
// to avoid potential costly look-aheads for closing tags we look inside the template itself
// we could change the syntax to self-closing tags, but that would make users cry
// the value found is cached
func isInnerShortcode(t *template.Template) (bool, error) {
	isInnerShortcodeCache.RLock()
	m, ok := isInnerShortcodeCache.m[t.Name()]
	isInnerShortcodeCache.RUnlock()

	if ok {
		return m, nil
	}

	isInnerShortcodeCache.Lock()
	defer isInnerShortcodeCache.Unlock()
	if t.Tree == nil {
		return false, errors.New("Template failed to compile")
	}
	match, _ := regexp.MatchString("{{.*?\\.Inner.*?}}", t.Tree.Root.String())
	isInnerShortcodeCache.m[t.Name()] = match

	return match, nil
}
Exemplo n.º 24
0
// 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
}
Exemplo n.º 25
0
// 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
}
Exemplo n.º 26
0
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
}
Exemplo n.º 27
0
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, path, err := readTemplate(name)
			if err != nil {
				return err
			}

			if _, err = tpl.New(path).Parse(content); err != nil {
				if strings.Contains(err.Error(), "redefinition of template") {
					return fmt.Errorf("A redefinition error raised while parsing [%s]. Did you happen to put the HTML comments outside the {{define}} block?)", name)
				}
				return err
			}

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

	return
}
Exemplo n.º 28
0
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
}
Exemplo n.º 29
0
// 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
}
Exemplo n.º 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
}