Exemple #1
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
}
Exemple #2
0
func (t *Template) ParseFile(file string, override bool) error {
	dir := ""
	var err error
	if !override {
		dir, err = os.Getwd()
		if err != nil {
			return err
		}
	}
	var tmpl *template.Template
	if t.HtmlTemplate == nil {

		tmpl, err = template.ParseFiles(dir + "/" + file)
		if err != nil {
			return err
		}
		tmpl.Funcs(t.FuncMap)
	} else {
		t.HtmlTemplate.Funcs(t.FuncMap)
		tmpl, err = t.HtmlTemplate.ParseFiles(dir + "/" + file)
		if err != nil {
			log.Println(err)
			return err
		}
	}
	t.HtmlTemplate = tmpl

	return err
}
Exemple #3
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
	})
}
Exemple #4
0
func (s *Server) parseTemplates() {

	var t *template.Template

	t = template.New("layout")
	t.Funcs(template.FuncMap{"ng": func(s string) string { return "{{" + s + "}}" }})

	_, err := t.ParseGlob(viewPath("**.html"))
	if err != nil {
		log.Fatal(err)
	}

	subdirs, _ := ioutil.ReadDir(viewPath(""))
	for _, dir := range subdirs {
		if !dir.IsDir() {
			continue
		}
		fullPath := viewPath(dir.Name())
		_, err := t.ParseGlob(path.Join(fullPath, "*.html"))
		if err != nil {
			log.Fatal(err)
		}
	}

	s.templates["layout"] = t

}
Exemple #5
0
func (v *View) getTemplateInstance(tpl []string) (*template.Template, error) {
	key := strings.Join(tpl, "-")
	// if IsCache, get cached template if exist
	if v.IsCache {
		if v.templateCache[key] != nil {
			return v.templateCache[key], nil
		}
	}
	var (
		t    *template.Template
		e    error
		file []string = make([]string, len(tpl))
	)
	for i, tp := range tpl {
		file[i] = path.Join(v.Dir, tp)
	}
	t = template.New(path.Base(tpl[0]))
	t.Funcs(v.FuncMap)
	t, e = t.ParseFiles(file...)
	if e != nil {
		return nil, e
	}
	if v.IsCache {
		v.templateCache[key] = t
	}
	return t, nil

}
Exemple #6
0
func (t *Template) ParseFile(file string, override bool) error {
	dir := ""
	var err error
	if !override {
		dir, err = os.Getwd()
		if err != nil {
			return err
		}
	}
	var tmpl *template.Template
	if t.HtmlTemplate == nil {

		tmpl, err = template.New(file).Funcs(t.FuncMap).ParseFiles(dir + "/" + file)
		if err != nil {
			return err
		}
		tmpl.Funcs(t.FuncMap)
	} else {
		// Make sure the FuncMap is added to the template before parsing the new file
		t.HtmlTemplate.Funcs(t.FuncMap)
		tmpl, err = t.HtmlTemplate.ParseFiles(dir + "/" + file)
		if err != nil {
			return err
		}
	}
	t.HtmlTemplate = tmpl

	return err
}
Exemple #7
0
func setFuncs(t *template.Template) *template.Template {
	t.Funcs(template.FuncMap{
		"inc":      inc,
		"split":    split,
		"gravatar": gravatar,
		"timeAgo":  timeAgo,
	})
	return t
}
Exemple #8
0
func (r *templateRender) addYield(t *template.Template, name string, binding interface{}) {
	funcs := template.FuncMap{
		"yield": func() (template.HTML, error) {
			buf, err := r.execute(t, name, binding)
			// return safe html here since we are rendering our own template
			return template.HTML(buf.String()), err
		},
	}
	t.Funcs(funcs)
}
Exemple #9
0
// applyFilters sets functions of template.
func applyFilters(t *template.Template, filters ...Filter) *template.Template {
	funcMap := template.FuncMap{}
	for _, filter := range filters {
		if filter.Func == nil {
			continue
		}
		funcMap[filter.Name] = filter.Func
	}
	return t.Funcs(funcMap)
}
Exemple #10
0
// AddRegisterFunc provides an easy to add function for getting a Register to your html/template.Template
func AddHtmlRegisterFunc(tmpl *htmltmpl.Template, name string) *htmltmpl.Template {
	if name == "" {
		name = "getregister"
	}
	tmpl.Funcs(map[string]interface{}{
		name: func() *Register {
			return NewRegister()
		},
	})
	return tmpl
}
Exemple #11
0
func (r *TplRender) addYield(t *template.Template, tplName string, data interface{}) {
	funcs := template.FuncMap{
		"yield": func() (template.HTML, error) {
			buf, err := r.execute(t, tplName, data)
			// return safe html here since we are rendering our own template
			return template.HTML(buf.String()), err
		},
		"current": func() (string, error) {
			return tplName, nil
		},
	}
	t.Funcs(funcs)
}
Exemple #12
0
// Same as Compile but allows to specify a template
func (c *Compiler) CompileWithTemplate(t *template.Template) (*template.Template, error) {
	data, err := c.CompileString()

	if err != nil {
		return nil, err
	}

	tpl, err := t.Funcs(FuncMap).Parse(data)

	if err != nil {
		return nil, err
	}

	return tpl, nil
}
Exemple #13
0
func RenderTemplate(w http.ResponseWriter, layout, name string, data interface{}) {
	templates := strings.Split(name, "/")
	if len(templates) != 2 {
		http.Error(w, "Wrong Render Path: "+name, http.StatusInternalServerError)
		return
	}
	var ts *template.Template
	var err error
	mainPath, err := filepath.Abs(viewConf.Folder + string(os.PathSeparator) + viewConf.LayoutFolder + string(os.PathSeparator) + layout + "." + viewConf.PostFix)
	if err != nil {
		http.Error(w, "Main File Abs Error: "+err.Error(), http.StatusInternalServerError)
		return
	}
	renderPath, err := filepath.Abs(viewConf.Folder + string(os.PathSeparator) + name + "." + viewConf.PostFix)
	if err != nil {
		http.Error(w, "Render File Abs Error: "+err.Error(), http.StatusInternalServerError)
		return
	}
	if viewConf.IsCache {
		tmpKey := layout + "_" + name
		var ok bool
		if ts, ok = cacheTmp[tmpKey]; ok {
			ts = cacheTmp[tmpKey]
		} else {
			if ts, err = template.ParseFiles(mainPath, renderPath); err != nil {
				http.Error(w, "Template Parse Error: "+err.Error(), http.StatusInternalServerError)
				return
			}
			cacheTmp[tmpKey] = ts
		}
	} else {
		if ts, err = template.ParseFiles(mainPath, renderPath); err != nil {
			http.Error(w, "Template Parse Error: "+err.Error(), http.StatusInternalServerError)
			return
		}
	}

	err = ts.Funcs(funcMaps).ExecuteTemplate(w, layout, data)
	if err != nil {
		http.Error(w, "Template Execute Error: "+err.Error(), http.StatusInternalServerError)
		return
	}
}
Exemple #14
0
// Add partial keyword
func addPartial(t *template.Template) {
	funcs := template.FuncMap{
		"partial": func(name string, pairs ...interface{}) (template.HTML, error) {
			binding, err := mapFromPairs(pairs...)

			if err != nil {
				return "", err
			}

			dir, filename := filepath.Split(name)

			buf, err := executeTemplate(t, dir+"_"+filename+".html", binding)

			// return safe html
			return template.HTML(buf.String()), err
		},
	}
	t.Funcs(funcs)
}
Exemple #15
0
func (this *View) getInstance(tpl string) (*template.Template, error) {
	if this.IsCache && this.templateCache[tpl] != nil {
		return this.templateCache[tpl], nil
	}
	var (
		t *template.Template
		e error
	)
	t = template.New(path.Base(tpl))
	t.Funcs(this.FuncMap)
	t, e = t.ParseFiles(path.Join(this.Dir, tpl))
	if e != nil {
		return nil, e
	}
	if this.IsCache {
		this.templateCache[tpl] = t
	}
	return t, nil
}
Exemple #16
0
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}
}
Exemple #18
0
func (t *Template) ParseFile(file string, override bool) error {
	dir := ""
	var err error
	if !override {
		dir, err = os.Getwd()
		if err != nil {
			return err
		}
	}
	var tmpl *template.Template
	if t.HtmlTemplate == nil {
		name := ""
		if nameArr := strings.Split(file, "/"); len(nameArr) > 0 {
			name = nameArr[len(nameArr)-1]
		}

		tmpl, err = template.New(name).Funcs(t.FuncMap).ParseFiles(dir + "/" + file)
		if err != nil {
			return err
		}
		tmpl.Funcs(t.FuncMap)
	} else {
		// Make sure the FuncMap is added to the template before parsing the new file
		t.HtmlTemplate.Funcs(t.FuncMap)
		tmpl, err = t.HtmlTemplate.ParseFiles(dir + "/" + file)
		if err != nil {
			return err
		}
	}
	t.HtmlTemplate = tmpl

	if err != nil {
		log.Println(err)
	}

	return err
}
Exemple #19
0
func registerDefaultFunctions(tmpl *template.Template) {
	m := make(map[string]TemplateFunc)
	registerTemplateFunc(m)
	tmpl.Funcs(convertTemplateFunc(m))

	m2 := make(map[string]TemplateFunc2)
	registerTemplateFunc2(m2)
	tmpl.Funcs(convertTemplateFunc2(m2))

	mc := make(map[string]TemplateCommonFunc)
	registerTemplateCommonFunc(mc)
	tmpl.Funcs(convertTemplateCommonFunc(mc))

	registerTemplateCommonModel(g_TEMPLATE_COMMON_MODEL)
	utils.Init(registerTemplateCommonModel)
}
Exemple #20
0
func RenderTemplate(w http.ResponseWriter, r *http.Request, page string, data map[string]interface{}) {
	if data == nil {
		data = map[string]interface{}{}
	}
	if _, ok := data["CurrentUser"]; !ok || (data["CurrentUser"].(*User) == nil) {
		data["CurrentUser"] = RequestUser(r)
	}
	data["Flash"] = r.URL.Query().Get("flash")
	data["Taglist"], _ = Dal.GetTags()
	if data["CurrentUser"].(*User) != nil {
		data["friendsList"], _ = Dal.GetFriendsList(data["CurrentUser"].(*User).UserId)
		data["ChatMessages"], _ = Dal.GetMessages(data["CurrentUser"].(*User).UserId)
	}
	var templateClone *template.Template

	renderFuncs := template.FuncMap{
		"RenderTemplateGameLink": func(game Game, href, onclick string) (template.HTML, error) {
			if href == "" {
				href = "/game/" + game.GameId
			}
			buf := bytes.NewBuffer(nil)
			err := templateClone.ExecuteTemplate(buf, "game/gamelink", map[string]interface{}{"GameLinkHREF": href, "GameLinkONCLICK": onclick, "Game": game})
			return template.HTML(buf.String()), err
		},
		"RenderTemplateRating": func(rating float64) (template.HTML, error) {
			buf := bytes.NewBuffer(nil)
			err := templateClone.ExecuteTemplate(buf, "review/rating", map[string]interface{}{"Rating": rating})
			return template.HTML(buf.String()), err
		},
		"RenderTemplateReview": func(rev Review) (template.HTML, error) {
			buf := bytes.NewBuffer(nil)
			err := templateClone.ExecuteTemplate(buf, "review/review", map[string]interface{}{"Review": rev, "CurrentUser": data["CurrentUser"]})
			return template.HTML(buf.String()), err
		},
		"RenderTemplateVideo": func(url, width, height interface{}) (template.HTML, error) {
			buf := bytes.NewBuffer(nil)
			err := templateClone.ExecuteTemplate(buf, "video/embed", map[string]interface{}{"VideoURL": url, "VideoWidth": width, "VideoHeight": height})
			return template.HTML(buf.String()), err
		},
		"RenderTemplateGameVideo": func(vid Video, width, height interface{}) (template.HTML, error) {
			buf := bytes.NewBuffer(nil)
			err := templateClone.ExecuteTemplate(buf, "video/gamevideo", map[string]interface{}{"Video": vid, "VideoWidth": width, "VideoHeight": height})
			return template.HTML(buf.String()), err
		},
		"RenderTemplateUserVideo": func(vid Video, width, height interface{}) (template.HTML, error) {
			buf := bytes.NewBuffer(nil)
			err := templateClone.ExecuteTemplate(buf, "video/uservideo", map[string]interface{}{"Video": vid, "VideoWidth": width, "VideoHeight": height})
			return template.HTML(buf.String()), err
		},
	}
	templateClone, _ = templates.Clone()
	templateClone.Funcs(renderFuncs)

	funcs := template.FuncMap{
		"yield": func() (template.HTML, error) {
			buf := bytes.NewBuffer(nil)
			err := templateClone.ExecuteTemplate(buf, page, data)
			return template.HTML(buf.String()), err
		},
		"yieldmenu": func() (template.HTML, error) {
			buf := bytes.NewBuffer(nil)
			err := laytemplates.ExecuteTemplate(buf, "menu", data)
			return template.HTML(buf.String()), err
		},
		"yieldchat": func() (template.HTML, error) {
			buf := bytes.NewBuffer(nil)
			err := laytemplates.ExecuteTemplate(buf, "chat", data)
			return template.HTML(buf.String()), err
		},
		"FindUserNameByID": layoutFuncs["FindUserNameByID"],
		"ReviewCount":      layoutFuncs["ReviewCount"],
		"VideoCount":       layoutFuncs["VideoCount"],
		"URLQueryEscaper":  layoutFuncs["URLQueryEscaper"],
		"JSONify":          layoutFuncs["JSONify"],
		"HTMLnewlines":     layoutFuncs["HTMLnewlines"],
	}
	layoutclone, _ := layout.Clone()
	layoutclone.Funcs(funcs).Funcs(renderFuncs)
	err := layoutclone.Execute(w, data)
	if err != nil {
		http.Error(w, fmt.Sprintf(errTemplate, html.EscapeString(page), html.EscapeString(err.Error())), http.StatusInternalServerError)
	}
}
Exemple #21
0
func (st *SweeTpl) assemble(name string) (rootTemplate *template.Template, assembleErr error) {
	defer func() {
		if r := recover(); r != nil {
			if err, ok := r.(error); ok {
				assembleErr = err
			} else {
				assembleErr = errors.New("Panic during assemble")
			}
		}
	}()

	stack := []*NamedTemplate{}

	err := st.add(&stack, name)
	if err != nil {
		return nil, err
	}

	// The stack is ordered 'general' to 'specific'

	blocks := map[string]string{}
	blockId := 0

	// Pick out all 'include' blocks and replace them with the raw
	// text from the requested template (using the configured template
	// directory as a base path)
	for _, namedTemplate := range stack {
		namedTemplate.Src = re_include.ReplaceAllStringFunc(namedTemplate.Src, func(raw string) string {
			parsed := re_include.FindStringSubmatch(raw)
			templatePath := parsed[1]
			if dirLoader, ok := st.Loader.(*DirLoader); ok {
				templatePath = path.Join(dirLoader.BasePath, templatePath)
			}
			f, err := os.Open(templatePath)
			if err != nil {
				panic(err)
			}
			body, err := ioutil.ReadAll(f)
			if err != nil {
				panic(err)
			}
			return string(body)
		})
	}

	// Pick out all 'define' blocks and replace them with UIDs.
	// The Map should contain the 'last' definition of each, which is the most specific
	// Must be done separate from below block to make sure all are replaced first.
	for _, namedTemplate := range stack {

		namedTemplate.Src = re_defineTag.ReplaceAllStringFunc(namedTemplate.Src, func(raw string) string {
			parsed := re_defineTag.FindStringSubmatch(raw)
			blockName := fmt.Sprintf("BLOCK_%d", blockId)
			blocks[parsed[1]] = blockName

			blockId += 1
			return "{{ define \"" + blockName + "\" }}"
		})
	}

	// 1) Pick out all 'template' blocks, and replace with the UID from above.
	// 2) Render
	for i, namedTemplate := range stack {
		namedTemplate.Src = re_templateTag.ReplaceAllStringFunc(namedTemplate.Src, func(raw string) string {
			parsed := re_templateTag.FindStringSubmatch(raw)
			origName := parsed[1]
			replacedName, ok := blocks[origName]

			// Default the import var to . if not set
			dot := "."
			if len(parsed) == 3 && len(parsed[2]) > 0 {
				dot = parsed[2]
			}
			if ok {
				return fmt.Sprintf(`{{ template "%s" %s }}`, replacedName, dot)
			} else {
				return ""
			}
		})
		var thisTemplate *template.Template

		if i == 0 {
			thisTemplate = template.New(namedTemplate.Name)
			rootTemplate = thisTemplate

		} else {
			thisTemplate = rootTemplate.New(namedTemplate.Name)
		}
		thisTemplate.Funcs(st.FuncMap) // Must be added before Parse.
		_, err := thisTemplate.Parse(namedTemplate.Src)
		if err != nil {
			return nil, err
		}

	}

	return rootTemplate, nil
}
Exemple #22
0
func addFunc(tpl *template.Template, preloadedTpl *template.Template) {
	funcmap, ok := templateFuncMap[preloadedTpl]
	if ok {
		tpl.Funcs(funcmap)
	}
}
Exemple #23
0
func Funcs(tpl *template.Template, funcmap template.FuncMap) {
	tpl.Funcs(funcmap)
	templateFuncMap[tpl] = funcmap
}
Exemple #24
0
// CompileResultWithTemplate compiles the parsed result and associates it with t.
func CompileResultWithTemplate(t *template.Template, rslt *result, opts *Options) (*template.Template, error) {
	// Initialize the options.
	opts = initializeOptions(opts)

	var err error

	// Create a buffer.
	baseBf := bytes.NewBuffer(nil)
	innerBf := bytes.NewBuffer(nil)
	includeBfs := make(map[string]*bytes.Buffer)

	// Write data to the buffer.
	for _, e := range rslt.base {
		if _, err := e.WriteTo(baseBf); err != nil {
			return nil, err
		}
	}

	for _, e := range rslt.inner {
		if _, err = e.WriteTo(innerBf); err != nil {
			return nil, err
		}
	}

	for path, elements := range rslt.includes {
		bf := bytes.NewBuffer(nil)

		// Write a define action.
		bf.WriteString(fmt.Sprintf(actionDefine, opts.DelimLeft, path, opts.DelimRight))

		for _, e := range elements {
			if _, err = e.WriteTo(bf); err != nil {
				return nil, err
			}
		}

		// Write an end action.
		bf.WriteString(fmt.Sprintf(actionEnd, opts.DelimLeft, opts.DelimRight))

		includeBfs[path] = bf
	}

	// Set Delimiters.
	t.Delims(opts.DelimLeft, opts.DelimRight)

	// Set FuncMaps.
	t.Funcs(template.FuncMap{
		preDefinedFuncNameHTML: func(s string) template.HTML {
			return template.HTML(s)
		},
	})

	t.Funcs(opts.FuncMap)

	// Parse a string to the template.
	t, err = t.Parse(baseBf.String())
	if err != nil {
		return nil, err
	}

	t, err = t.Parse(innerBf.String())
	if err != nil {
		return nil, err
	}

	for _, bf := range includeBfs {
		t, err = t.Parse(bf.String())
		if err != nil {
			return nil, err
		}
	}

	return t, nil
}
Exemple #25
0
func loadTemplates(funcMap template.FuncMap) (map[string]*template.Template, error) {
	lock.Lock()
	defer lock.Unlock()

	templates := make(map[string]*template.Template)

	err := filepath.Walk(basePath, func(path string, fi os.FileInfo, err error) error {
		r, err := filepath.Rel(basePath, path)
		if err != nil {
			return err
		}

		ext := getExt(r)

		for _, extension := range exts {
			if ext == extension {
				if err := add(path); err != nil {
					panic(err)
				}

				// Now we find all regular template definitions and check for the most recent definiton
				for _, t := range regularTemplateDefs {
					found := false
					defineIdx := 0
					// From the beginning (which should) most specifc we look for definitions
					for _, nt := range cache {
						nt.Src = re_defineTag.ReplaceAllStringFunc(nt.Src, func(raw string) string {
							parsed := re_defineTag.FindStringSubmatch(raw)
							name := parsed[1]
							if name != t {
								return raw
							}
							// Don't touch the first definition
							if !found {
								found = true
								return raw
							}

							defineIdx += 1

							return fmt.Sprintf("{{ define \"%s_invalidated_#%d\" }}", name, defineIdx)
						})
					}
				}

				var (
					baseTmpl *template.Template
					i        int
				)

				for _, nt := range cache {
					var currentTmpl *template.Template
					if i == 0 {
						baseTmpl = template.New(nt.Name)
						currentTmpl = baseTmpl
					} else {
						currentTmpl = baseTmpl.New(nt.Name)
					}

					template.Must(currentTmpl.Funcs(funcMap).Parse(nt.Src))
					i++
				}
				tname := generateTemplateName(basePath, path)
				templates[tname] = baseTmpl

				// Make sure we empty the cache between runs
				cache = cache[0:0]

				break
				//return nil
			}
		}
		return nil

	})

	return templates, err
}
Exemple #26
0
// Pre-parse step to process HTML templates and add functions for templates to execute:
func uiTemplatesPreParse(tmpl *template.Template) *template.Template {
	log_info("Parsing HTML template files\n")
	return tmpl.Funcs(templateFunctions)
}
Exemple #27
0
// changes from https://github.com/go-macaron/renders/blob/master/renders.go#L43,
// thanks a lot
func (th *Theme) loadTemplates() error {
	th.lock.Lock()
	defer th.lock.Unlock()

	templates := make(map[string]*template.Template)

	err := filepath.Walk(th.dir, func(p string, fi os.FileInfo, err error) error {
		r, err := filepath.Rel(th.dir, p) // get relative path
		if err != nil {
			return err
		}
		ext := getExt(r)
		for _, extension := range th.extensions {
			if ext == extension {
				if err := th.add(p); err != nil {
					return err
				}
				for _, t := range th.regularTemplateDefs {
					found := false
					defineIdx := 0
					// From the beginning (which should) most specifc we look for definitions
					for _, nt := range th.cache {
						nt.Src = re_defineTag.ReplaceAllStringFunc(nt.Src, func(raw string) string {
							parsed := re_defineTag.FindStringSubmatch(raw)
							name := parsed[1]
							if name != t {
								return raw
							}
							// Don't touch the first definition
							if !found {
								found = true
								return raw
							}

							defineIdx += 1

							return fmt.Sprintf("{{ define \"%s_invalidated_#%d\" }}", name, defineIdx)
						})
					}
				}

				var (
					baseTmpl *template.Template
					i        int
				)

				for _, nt := range th.cache {
					var currentTmpl *template.Template
					if i == 0 {
						baseTmpl = template.New(nt.Name)
						currentTmpl = baseTmpl
					} else {
						currentTmpl = baseTmpl.New(nt.Name)
					}

					template.Must(currentTmpl.Funcs(th.funcMap).Parse(nt.Src))
					i++
				}
				tname := generateTemplateName(th.dir, p)
				templates[tname] = baseTmpl

				// Make sure we empty the cache between runs
				th.cache = th.cache[0:0]

				break
				//return nil
			}
		}
		return nil
	})
	th.templates = templates
	return err
}
Exemple #28
0
func (o *opFuncs) Run(t *htmlTmpl.Template) (*htmlTmpl.Template, error) {
	return t.Funcs(o.funcs), nil
}
func main() {
	var help bool
	var bindto, config_file string
	var config_contents []byte
	var application_tmpl, memberlist_tmpl, print_tmpl *template.Template
	var unique_member_detail_template *template.Template
	var authenticator *ancientauth.Authenticator
	var debug_authenticator bool
	var config membersys.MembersysConfig
	var db *membersys.MembershipDB
	var err error

	flag.BoolVar(&help, "help", false, "Display help")
	flag.StringVar(&bindto, "bind", "127.0.0.1:8080",
		"The address to bind the web server to")
	flag.StringVar(&config_file, "config", "",
		"Path to a file containing a MembersysConfig protocol buffer")
	flag.BoolVar(&debug_authenticator, "debug-authenticator", false,
		"Debug the authenticator?")
	flag.Parse()

	if help || config_file == "" {
		flag.Usage()
		os.Exit(1)
	}

	config_contents, err = ioutil.ReadFile(config_file)
	if err != nil {
		log.Fatal("Unable to read ", config_file, ": ", err)
	}
	err = proto.Unmarshal(config_contents, &config)
	if err != nil {
		err = proto.UnmarshalText(string(config_contents), &config)
	}
	if err != nil {
		log.Fatal("Error parsing ", config_file, ": ", err)
	}

	// Load and parse the HTML templates to be displayed.
	application_tmpl, err = template.ParseFiles(
		config.GetTemplateDir() + "/form.html")
	if err != nil {
		log.Fatal("Unable to parse form template: ", err)
	}

	print_tmpl, err = template.ParseFiles(
		config.GetTemplateDir() + "/printlayout.html")
	if err != nil {
		log.Fatal("Unable to parse print layout template: ", err)
	}

	memberlist_tmpl = template.New("memberlist")
	memberlist_tmpl.Funcs(fmap)
	memberlist_tmpl, err = memberlist_tmpl.ParseFiles(
		config.GetTemplateDir() + "/memberlist.html")
	if err != nil {
		log.Fatal("Unable to parse member list template: ", err)
	}

	unique_member_detail_template = template.New("memberdetail")
	unique_member_detail_template.Funcs(fmap)
	unique_member_detail_template, err =
		unique_member_detail_template.ParseFiles(
			config.GetTemplateDir() + "/memberdetail.html")
	if err != nil {
		log.Fatal("Unable to parse member detail template: ", err)
	}

	authenticator, err = ancientauth.NewAuthenticator(
		config.AuthenticationConfig.GetAppName(),
		config.AuthenticationConfig.GetCertPath(),
		config.AuthenticationConfig.GetKeyPath(),
		config.AuthenticationConfig.GetCaBundlePath(),
		config.AuthenticationConfig.GetAuthServerHost(),
		config.AuthenticationConfig.GetX509KeyserverHost(),
		int(config.AuthenticationConfig.GetX509CertificateCacheSize()))
	if err != nil {
		log.Fatal("Unable to assemble authenticator: ", err)
	}

	if debug_authenticator {
		authenticator.Debug()
	}

	db, err = membersys.NewMembershipDB(
		config.DatabaseConfig.GetDatabaseServer(),
		config.DatabaseConfig.GetDatabaseName(),
		time.Duration(config.DatabaseConfig.GetDatabaseTimeout())*time.Millisecond)
	if err != nil {
		log.Fatal("Unable to connect to the cassandra DB ",
			config.DatabaseConfig.GetDatabaseServer(), " at ",
			config.DatabaseConfig.GetDatabaseName(), ": ", err)
	}

	// Register the URL handlers to be invoked.
	http.Handle("/admin/api/members", &MemberListHandler{
		admingroup: config.AuthenticationConfig.GetAuthGroup(),
		auth:       authenticator,
		database:   db,
		pagesize:   config.GetResultPageSize(),
	})

	http.Handle("/admin/api/applicants", &ApplicantListHandler{
		admingroup: config.AuthenticationConfig.GetAuthGroup(),
		auth:       authenticator,
		database:   db,
		pagesize:   config.GetResultPageSize(),
	})

	http.Handle("/admin/api/queue", &MemberQueueListHandler{
		admingroup: config.AuthenticationConfig.GetAuthGroup(),
		auth:       authenticator,
		database:   db,
		pagesize:   config.GetResultPageSize(),
	})

	http.Handle("/admin/api/dequeue", &MemberDeQueueListHandler{
		admingroup: config.AuthenticationConfig.GetAuthGroup(),
		auth:       authenticator,
		database:   db,
		pagesize:   config.GetResultPageSize(),
	})

	http.Handle("/admin/api/trash", &MemberTrashListHandler{
		admingroup: config.AuthenticationConfig.GetAuthGroup(),
		auth:       authenticator,
		database:   db,
		pagesize:   config.GetResultPageSize(),
	})

	http.Handle("/admin/api/accept", &MemberAcceptHandler{
		admingroup: config.AuthenticationConfig.GetAuthGroup(),
		auth:       authenticator,
		database:   db,
	})

	http.Handle("/admin/api/reject", &MemberRejectHandler{
		admingroup: config.AuthenticationConfig.GetAuthGroup(),
		auth:       authenticator,
		database:   db,
	})

	http.Handle("/admin/api/editfee", &MemberFeeHandler{
		admingroup: config.AuthenticationConfig.GetAuthGroup(),
		auth:       authenticator,
		database:   db,
	})

	http.Handle("/admin/api/agreement-upload", &MemberAgreementUploadHandler{
		admingroup: config.AuthenticationConfig.GetAuthGroup(),
		auth:       authenticator,
		database:   db,
	})

	http.Handle("/admin/api/cancel-queued", &MemberQueueCancelHandler{
		admingroup: config.AuthenticationConfig.GetAuthGroup(),
		auth:       authenticator,
		database:   db,
	})

	http.Handle("/admin/api/goodbye-member", &MemberGoodbyeHandler{
		admingroup: config.AuthenticationConfig.GetAuthGroup(),
		auth:       authenticator,
		database:   db,
	})

	http.Handle("/admin/api/member", &MemberDetailHandler{
		admingroup: config.AuthenticationConfig.GetAuthGroup(),
		auth:       authenticator,
		database:   db,
	})

	http.Handle("/admin", &TotalListHandler{
		admingroup:           config.AuthenticationConfig.GetAuthGroup(),
		auth:                 authenticator,
		database:             db,
		pagesize:             config.GetResultPageSize(),
		template:             memberlist_tmpl,
		uniqueMemberTemplate: unique_member_detail_template,
	})

	http.HandleFunc("/barcode", MakeBarcode)

	http.Handle("/", &FormInputHandler{
		applicationTmpl: application_tmpl,
		database:        db,
		passthrough:     http.FileServer(http.Dir(config.GetTemplateDir())),
		printTmpl:       print_tmpl,
		useProxyRealIP:  config.GetUseProxyRealIp(),
	})

	err = http.ListenAndServe(bindto, nil)
	if err != nil {
		log.Fatal("ListenAndServe: ", err)
	}
}
Exemple #30
0
// Attach sets ScriptTag, LinkTag and Stastic as, respectively, scripttag, linktag and static template functions.
func (st *Static) Attach(tmpl *template.Template) {
	tmpl.Funcs(st.FuncMap())
}