示例#1
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
}
示例#2
0
func (r *TemplateRender) initTemplates(t *template.Template, tmps []string, exclude *[]string) error {
	firstLevel := 0 == len(*exclude)
	for tkey, tpl := range r.prepareTemplates(tmps...) {
		if nil == t.Lookup(tkey) {
			if data, err := ioutil.ReadFile(tpl); nil == err {
				tmps := templatesRegex.FindAllStringSubmatch(string(data), -1)

				ntemplates := []string{}
				if nil != tmps && len(tmps) > 0 {
					for _, it := range tmps {
						if sIndexOf(it[1], *exclude) < 0 {
							*exclude = append(*exclude, it[1])
							ntemplates = append(ntemplates, it[1])
						}
					}
				}

				// Prepare new templates
				if len(ntemplates) > 0 {
					if err = r.initTemplates(t, ntemplates, exclude); nil != err {
						return err
					}
				}

				if _, err = t.New(tkey).Parse(string(data)); nil != err {
					return err
				}
			} else if firstLevel {
				return err
			}
		}
	}
	return nil
}
示例#3
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
}
示例#4
0
func LoadPartialTemplates(appDir string, partialTemplatePaths []string, collectorTemplate *template.Template) *template.Template {
	if len(partialTemplatePaths) < 1 {
		log.Printf("Expect partial templates to be len > 0")
		return collectorTemplate
	}
	for _, path := range partialTemplatePaths {
		input, err := ioutil.ReadFile(path)
		if err != nil {
			log.Print(err)
			continue
		}

		//HACK revisit using template.Must
		//collectorTemplate, err = collectorTemplate.Clone()
		if err != nil {
			log.Printf("Error was %s \n", err)
			return collectorTemplate
		}
		name := ConvertTemplateName(appDir, path)
		//fmt.Printf("templateName = %s \n", name)
		collectorTemplate = template.Must(collectorTemplate.New(name).Parse(string(input)))
	}

	//TODO add this loop when debug flag is supported
	// for _, tp := range collectorTemplate.Templates() {
	// 	fmt.Printf("tp.Name = %s \n", tp.Name())
	// }
	return collectorTemplate
}
示例#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
}
示例#6
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
}
示例#7
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
}
示例#8
0
文件: template.go 项目: elago/ela
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
}
示例#9
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
}
示例#10
0
文件: template.go 项目: no2key/her
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
	})
}
示例#11
0
func (v *Views) loadTemplate(name, content string, t *template.Template) {
	log.Println("loaded template", name)
	_, err := t.New(name).Parse(content)
	if err != nil {
		log.Panic(err)
	}
}
示例#12
0
// loadTemplates walks sourceDir and loads all base templates into t.  These
// are files that have a '.tmpl' extensions and a leading underscore.  The
// template name is the filename with those stripped.
func loadBaseTemplates(t *template.Template) error {
	return filepath.Walk(*sourceDir, func(path string, info os.FileInfo, err error) error {
		if err != nil {
			return err
		}
		if info.IsDir() {
			return nil
		}

		basename := filepath.Base(path)
		// Only handle files that start with _
		if !strings.HasPrefix(basename, "_") {
			return nil
		}

		// Only handle files with ".tmpl" extension
		ext := filepath.Ext(basename)
		if ext != ".tmpl" {
			return nil
		}

		fmt.Printf("Loading template file: %v\n", path)

		// Strip off "_" and ".tmpl"
		name := strings.TrimPrefix(strings.TrimSuffix(basename, filepath.Ext(basename)), "_")
		data, err := ioutil.ReadFile(path)
		_, err = t.New(name).Parse(string(data))
		if err != nil {
			return err
		}
		return nil
	})
}
示例#13
0
func (f *RestHtmlFormattor) getMethodTemplate(m *template.Template, rest *RestContext) *template.Template {
	t := m.Lookup(rest.Method + f.dotsuffix)
	var err error
	if t == nil {
		t, err = m.New(rest.Method + f.dotsuffix).ParseFiles(filepath.Join(document_root, rest.Url, rest.Method+f.dotsuffix))
		if err != nil {
			fmt.Println("ERROR template.ParseFile: %v", err)
		}
	}
	return t
}
示例#14
0
func parseTemplate(name string, content string) {
	if tmpl == nil {
		tmpl = template.New(name)
	}
	var t *template.Template
	if tmpl.Name() == name {
		t = tmpl
	} else {
		t = tmpl.New(name)
	}
	template.Must(t.New(name).Delims("[[", "]]").Parse(content))
}
示例#15
0
文件: vfiles.go 项目: influx6/assets
// LoadVirtualTemplateFile loads up a virtualfile into a template
func LoadVirtualTemplateFile(vf *VFile, tree *template.Template) (*template.Template, error) {
	contents, ex := vf.Data()

	if ex != nil {
		return nil, ex
	}

	tl := tree.New(vf.Name())

	tl, ex = tl.Parse(string(contents))

	return tl, ex
}
示例#16
0
//something like template.ParseFile but in memory
func FileSet(t *template.Template, templs []TemplateFile) (ot *template.Template, err error) {
	for _, file := range templs {
		if t == nil {
			t, err = template.New(file.Name).Parse(file.Content)
			if err != nil {
				return nil, fmt.Errorf("[kmgHtmlTemplate.FileSet] template.Parse name[%s] err:%s", file.Name, err)
			}
			continue
		}
		_, err = t.New(file.Name).Parse(file.Content)
		if err != nil {
			return nil, fmt.Errorf("[kmgHtmlTemplate.FileSet] template.Parse name[%s] err:%s", file.Name, err)
		}
	}
	return t, nil
}
示例#17
0
func (h *HtmlRender) initTemplate(parent *template.Template, dir string, typ string) {
	parent.New("")
	if !h.saveTemp { //for debug
		log.Println("init template in ", h.dir, dir, "helper")
	}
	//scan for the helpers
	filepath.Walk(filepath.Join(h.dir, dir, "helper"), func(path string, info os.FileInfo, err error) error {
		if err == nil && (!info.IsDir()) && strings.HasSuffix(info.Name(), h.suffix) {
			name := strings.TrimSuffix(info.Name(), h.suffix)
			log.Printf("Parse helper:%s(%s)", typ+"/"+name, path)
			e := parseFileWithName(parent, typ+"/"+name, path)
			if e != nil {
				fmt.Printf("ERROR template.ParseFile: %v", e)
			}
		}
		return nil
	})
}
示例#18
0
func LoadTemplates(templates *template.Template, list ...string) {
	templateBox, err := rice.FindBox(".")
	if err != nil {
		log.Fatal(err)
	}
	funcMap := template.FuncMap{
		"add": func(x, y int) int { return x + y },
	}
	for _, x := range list {
		templateString, err := templateBox.String(x)
		if err != nil {
			log.Fatal(err)
		}
		_, err = templates.New(strings.Join([]string{"admin/", x}, "")).Funcs(funcMap).Parse(templateString)
		if err != nil {
			log.Fatal(err)
		}
	}
}
示例#19
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
}
示例#20
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
}
示例#21
0
// loadTemplate is responsible for loading a single template and associating it
// with t. It reads the template file from g.ReadFile as appropriate.
func (g *Generator) loadTemplate(t *template.Template, tmplPath string) (*template.Template, error) {
	// Make the filepath relative to the filemap.
	tmplPath = g.FileMap.relative(tmplPath)[0]

	// Determine the open function.
	readFile := g.ReadFile
	if readFile == nil {
		readFile = ioutil.ReadFile
	}

	// Read the file.
	data, err := readFile(tmplPath)
	if err != nil {
		return nil, err
	}

	// Create a new template and parse.
	_, name := path.Split(tmplPath)
	return t.New(name).Parse(string(data))
}
示例#22
0
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
func NewSunnyPublisher(p string) *SunnyPublisher {
	var htmpl *htemplate.Template = htemplate.New("index.html")
	var tmpl *template.Template = template.New("index")
	var plen int = 0

	if strings.Contains(p, `\`) {
		p = strings.Replace(p, `\`, "/", -1)
	} else if p == "" {
		p = DEFAULT_VIEWPATH
	}

	if plen = len(p); p[plen-1] != "/" {
		p = p + "/"
		plen += 1
	}

	filepath.Walk(p, func(path string, info os.FileInfo, err error) error {
		if err == nil && !info.IsDir() {
			b, err := ioutil.ReadFile(path)

			if err == nil {
				if strings.HasSuffix(info.Name(), ".html") {
					htmpl.New(path[plen:]).Parse(string(b))
				} else {
					tmpl.New(path[plen:]).Parse(string(b))
				}
			}
		}

		return nil
	})

	return &SunnyPublisher{
		renderer: make(map[string]Renderer),
		htmpl:    htmpl,
		tmpl:     tmpl,
	}
}
示例#24
0
文件: render.go 项目: jmptrader/bongo
func loadTheme(base, name string, tpl *template.Template) error {
	themesDir := filepath.Join(base, ThemeDir)
	return filepath.Walk(filepath.Join(themesDir, name), func(path string, info os.FileInfo, err error) error {
		if err != nil {
			return err
		}
		if info.IsDir() || !HasExt(path, defalutTplExtensions...) {
			return nil
		}
		b, err := ioutil.ReadFile(path)
		if err != nil {
			return err
		}
		n := strings.TrimPrefix(path, themesDir)
		tx := tpl.New(n[1:])
		_, err = tx.Parse(string(b))
		if err != nil {
			return err
		}
		return nil
	})

}
示例#25
0
func (vc *viewContainer) getTemplateDeep(file, viewExt, parent string, t *template.Template) (*template.Template, [][]string, error) {
	var fileAbsPath string
	if filepath.HasPrefix(file, "../") {
		fileAbsPath = filepath.Join(vc.viewDir, filepath.Dir(parent), file)
	} else {
		fileAbsPath = filepath.Join(vc.viewDir, file)
	}
	if e := IsFile(fileAbsPath); !e {
		return nil, [][]string{}, errNotFoundTpl(file)
	}
	data, err := ioutil.ReadFile(fileAbsPath)
	if err != nil {
		return nil, [][]string{}, err
	}
	t, err = t.New(file).Parse(string(data))
	if err != nil {
		return nil, [][]string{}, err
	}
	reg := regexp.MustCompile("{{" + "[ ]*template[ ]+\"([^\"]+)\"")
	allSub := reg.FindAllStringSubmatch(byte2Str(data), -1)
	for _, m := range allSub {
		if len(m) == 2 {
			look := t.Lookup(m[1])
			if look != nil {
				continue
			}
			if !strings.HasSuffix(strings.ToLower(m[1]), viewExt) {
				continue
			}
			t, _, err = vc.getTemplateDeep(m[1], viewExt, file, t)
			if err != nil {
				return nil, [][]string{}, err
			}
		}
	}
	return t, allSub, nil
}
示例#26
0
func getTplDeep(root, file, parent string, t *template.Template) (*template.Template, [][]string, error) {
	var fileAbsPath string
	if filepath.HasPrefix(file, "../") {
		fileAbsPath = filepath.Join(root, filepath.Dir(parent), file)
	} else {
		fileAbsPath = filepath.Join(root, file)
	}
	if e := utils.FileExists(fileAbsPath); !e {
		panic("can't find template file:" + file)
	}
	data, err := ioutil.ReadFile(fileAbsPath)
	if err != nil {
		return nil, [][]string{}, err
	}
	t, err = t.New(file).Parse(string(data))
	if err != nil {
		return nil, [][]string{}, err
	}
	reg := regexp.MustCompile(BConfig.WebConfig.TemplateLeft + "[ ]*template[ ]+\"([^\"]+)\"")
	allSub := reg.FindAllStringSubmatch(string(data), -1)
	for _, m := range allSub {
		if len(m) == 2 {
			tl := t.Lookup(m[1])
			if tl != nil {
				continue
			}
			if !HasTemplateExt(m[1]) {
				continue
			}
			t, _, err = getTplDeep(root, m[1], file, t)
			if err != nil {
				return nil, [][]string{}, err
			}
		}
	}
	return t, allSub, nil
}
示例#27
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
}
示例#28
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
}
示例#29
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
}
示例#30
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
}