예제 #1
1
func (s *server) executeTemplate(t *template.Template, context interface{}) ([]byte, error) {
	var buf bytes.Buffer
	if err := t.Execute(&buf, context); err != nil {
		return nil, err
	}
	return buf.Bytes(), nil
}
예제 #2
0
파일: handlers.go 프로젝트: Ryman/check
func BulkHandler(Layout *template.Template, Exits *Exits) func(http.ResponseWriter, *http.Request) {

	return func(w http.ResponseWriter, r *http.Request) {

		ip := r.URL.Query().Get("ip")
		if net.ParseIP(ip) == nil {
			if err := Layout.ExecuteTemplate(w, "bulk.html", nil); err != nil {
				http.Error(w, err.Error(), http.StatusInternalServerError)
			}
			return
		}

		port_str := r.URL.Query().Get("port")
		port, err := strconv.Atoi(port_str)
		port_str = "&port=" + port_str
		if err != nil {
			port = 80
			port_str = ""
		}

		str := fmt.Sprintf("# This is a list of all Tor exit nodes that can contact %s on Port %d #\n", ip, port)
		str += fmt.Sprintf("# You can update this list by visiting https://check.torproject.org/cgi-bin/TorBulkExitList.py?ip=%s%s #\n", ip, port_str)
		str += fmt.Sprintf("# This file was generated on %v #\n", Exits.UpdateTime.UTC().Format(time.UnixDate))
		str += Exits.Dump(ip, port)
		fmt.Fprintf(w, str)

	}

}
예제 #3
0
파일: fileserver.go 프로젝트: rawbite/devd
func notFound(ci inject.CopyInject, templates *template.Template, w http.ResponseWriter) error {
	err := ci.ServeTemplate(http.StatusNotFound, w, templates.Lookup("404.html"), nil)
	if err != nil {
		return err
	}
	return nil
}
예제 #4
0
파일: handler.go 프로젝트: mommel/eremetic
func renderHTML(w http.ResponseWriter, r *http.Request, task types.EremeticTask, taskID string) {
	var err error
	var tpl *template.Template

	data := make(map[string]interface{})
	funcMap := template.FuncMap{
		"ToLower": strings.ToLower,
	}

	if task == (types.EremeticTask{}) {
		tpl, err = template.ParseFiles("templates/error_404.html")
		data["TaskID"] = taskID
	} else {
		tpl, err = template.New("task.html").Funcs(funcMap).ParseFiles("templates/task.html")
		data = makeMap(task)
	}

	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		log.Error(err.Error())
		return
	}

	err = tpl.Execute(w, data)
}
예제 #5
0
파일: view.go 프로젝트: Lao-liu/GoInk
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

}
예제 #6
0
파일: views.go 프로젝트: timtadh/cc-survey
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)
	}
}
예제 #7
0
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
}
예제 #8
0
// Pase files match the [pattern] and store file path of each template name in templateMapPaths
func ParseGlob(templates *template.Template, pattern string) (*template.Template, error) {
	filePaths, err := filepath.Glob(pattern)
	if err != nil {
		return templates, err
	}

	if len(filePaths) == 0 {
		return templates, fmt.Errorf("mangotemplate.ParseGlob: pattern matches no files: %#q", pattern)
	}

	for _, path := range filePaths {
		_, err := templates.ParseFiles(path)
		if err != nil {
			return templates, err
		}

		for _, parsedTemplate := range templates.Templates() {
			if _, ok := templateMapPaths[parsedTemplate.Name()]; ok {
				continue
			}
			templateMapPaths[parsedTemplate.Name()] = path
		}
	}

	return templates, nil
}
예제 #9
0
파일: users.go 프로젝트: patrickjr/poker2
func renderTemplate(w http.ResponseWriter, tName string, tType *template.Template, dataObj interface{}) {

	err := tType.ExecuteTemplate(w, tName+".html", dataObj)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
	}
}
예제 #10
0
파일: status.go 프로젝트: 2722/lantern
// ErrorAccessingPage creates and returns a generic "error accessing page" error.
func ErrorAccessingPage(server string, errMessage error) ([]byte, error) {
	var err error
	var buf []byte
	var tmpl *template.Template

	if errMessage == nil {
		errMessage = errors.New("Unknown error.")
	}

	buf, err = Asset("generic_error.html")

	if err != nil {
		return nil, err
	}

	tmpl, err = template.New("status_error").Parse(string(buf))
	if err != nil {
		return nil, err
	}

	data := errorAccesingPageT{
		ServerName:   server,
		ErrorMessage: normalizeError(errMessage),
	}

	out := bytes.NewBuffer(nil)

	if err = tmpl.Execute(out, data); err != nil {
		return nil, err
	}

	return out.Bytes(), nil
}
예제 #11
0
func (h *Handler) Apply(w http.ResponseWriter, t *template.Template, tName string, app interface{}) (err error) {
	err = t.ExecuteTemplate(w, tName, app)
	if my, bad := mybad.Check(err, "template execution failure", "name", tName); bad {
		return my
	}
	return nil
}
예제 #12
0
파일: actions.go 프로젝트: DeyV/go-newsagg
func actionCategories(w http.ResponseWriter, req *http.Request) {
	var templActionCategories *template.Template = template.Must(
		template.ParseGlob("templates/categories/*.html"))

	wr := &HtmlContainer{}

	// templActionHome.Funcs(template.FuncMap{"len": Len})
	data := HtmlAssigner{
		"List": category.GetTagCloud(),
		"Test": "Test",
	}

	err := templActionCategories.Execute(wr, data)
	if err != nil {
		fmt.Errorf("%v", err)
	}

	lay := getLayoutTemplates()
	lay.New("title").Parse("Lista Kategorii - " + config.GetStringDef("page", "title", ""))

	err = lay.Execute(w, wr.getHtml())
	if err != nil {
		fmt.Errorf("%v", err)
	}
}
예제 #13
0
파일: actions.go 프로젝트: DeyV/go-newsagg
func actionCategoryList(w http.ResponseWriter, req *http.Request) {

	Id := req.URL.Query().Get("id")
	fmt.Println(Id)

	// // param := req.Vars()
	// catId, ok := param["id"]
	// if ok == nil {
	// 	catId = 0
	// }

	var templActionHome *template.Template = template.Must(
		template.ParseGlob("templates/home/*.html"))

	lay := getLayoutTemplates()
	wr := &HtmlContainer{}

	// templActionHome.Funcs(template.FuncMap{"len": Len})
	data := HtmlAssigner{
		"List": getEntryList("", 10),
		"Test": "Test",
	}

	err := templActionHome.Execute(wr, data)
	if err != nil {
		fmt.Errorf("%v", err)
	}

	lay.New("title").Parse("Najnowsze wpisy - " + config.GetStringDef("page", "title", ""))

	err = lay.Execute(w, wr.getHtml())
	if err != nil {
		fmt.Errorf("%v", err)
	}
}
예제 #14
0
파일: actions.go 프로젝트: DeyV/go-newsagg
func actionHome(w http.ResponseWriter, req *http.Request) {

	var templActionHome *template.Template = template.Must(
		template.ParseGlob("templates/home/*.html"))

	lay := getLayoutTemplates()
	wr := &HtmlContainer{}

	// templActionHome.Funcs(template.FuncMap{"len": Len})
	data := HtmlAssigner{
		"List": getEntryList("", 10),
		"Test": "Test",
	}

	err := templActionHome.Execute(wr, data)
	if err != nil {
		fmt.Errorf("%v", err)
	}

	lay.New("title").Parse("Najnowsze wpisy - " + config.GetStringDef("page", "title", ""))

	err = lay.Execute(w, wr.getHtml())
	if err != nil {
		fmt.Errorf("%v", err)
	}
}
예제 #15
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
}
예제 #16
0
파일: fs.go 프로젝트: twocool/srvdir
func dirList(w http.ResponseWriter, f File, name string, tmpl *template.Template) {
	w.Header().Set("Content-Type", "text/html; charset=utf-8")

	var contents []string
	for {
		dirs, err := f.Readdir(100)
		if err != nil || len(dirs) == 0 {
			break
		}
		for _, d := range dirs {
			name := d.Name()
			if d.IsDir() {
				name += "/"
			}

			contents = append(contents, name)
		}
	}

	tmpl.Execute(w, &struct {
		Name     string
		Contents []string
	}{
		Name:     name,
		Contents: contents,
	})
}
예제 #17
0
파일: main.go 프로젝트: x4rMa/admin-1
func (b *BaseField) BaseRender(w io.Writer, tmpl *template.Template, value interface{}, errStr string, startRow bool, ctx map[string]interface{}) {
	if ctx == nil {
		ctx = map[string]interface{}{}
	}
	ctx["label"] = b.Label
	ctx["blank"] = b.Blank
	ctx["name"] = b.Name
	ctx["value"] = value
	ctx["error"] = errStr
	ctx["help"] = b.Help
	ctx["startrow"] = startRow
	if b.Width == 0 {
		b.Width = 12
	}
	ctx["width"] = b.Width

	var buf bytes.Buffer
	tmpl.Execute(&buf, ctx)
	ctx["field"] = template.HTML(buf.String())

	err := fieldWrapper.Execute(w, ctx)
	if err != nil {
		fmt.Println(err)
	}
}
예제 #18
0
파일: fileserver.go 프로젝트: npk/devd
func dirList(ci inject.CopyInject, logger termlog.Logger, w http.ResponseWriter, name string, f http.File, templates *template.Template) {
	w.Header().Set("Cache-Control", "no-store, must-revalidate")
	files, err := f.Readdir(0)
	if err != nil {
		logger.Shout("Error reading directory for listing: %s", err)
		return
	}
	data := dirData{Name: name, Files: files}
	buff := bytes.NewBuffer(make([]byte, 0, 0))
	err = templates.Lookup("dirlist.html").Execute(buff, data)
	length := buff.Len()
	if err != nil {
		logger.Shout("Error producing directory listing: %s", err)
	}
	inj, err := ci.Sniff(buff)
	if err != nil {
		logger.Shout("Failed to inject in dir listing: %s", err)
		return
	}
	w.Header().Set(
		"Content-Length", fmt.Sprintf("%d", length+inj.Extra()),
	)
	_, err = inj.Copy(w)
	if err != nil {
		logger.Shout("Failed to inject in dir listing: %s", err)
		return
	}
}
예제 #19
0
파일: downloads-page.go 프로젝트: yl10/goxc
func RunTemplate(reportFilename, templateFile, templateText string, out *os.File, data interface{}, format string) (err error) {
	var tmpl *template.Template
	var htmpl *htemplate.Template
	if templateFile != "" {
		if format == "html" {
			htmpl, err = htemplate.New(templateFile).ParseGlob(templateFile)
		} else {
			tmpl, err = template.New(templateFile).ParseGlob(templateFile)
		}
	} else {
		if format == "html" {
			htmpl, err = htemplate.New(reportFilename).Parse(templateText)
		} else {
			tmpl, err = template.New(reportFilename).Parse(templateText)
		}
	}
	if err != nil {
		return err
	}
	if format == "html" {
		err = htmpl.Execute(out, data)
	} else {
		err = tmpl.Execute(out, data)
	}
	if err != nil {
		return err
	}

	return err
}
예제 #20
0
파일: templates.go 프로젝트: gopk/templates
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
}
예제 #21
0
// pageTitle executes "title" template and returns its result or defaultTitle.
func pageTitle(t *html.Template) string {
	b := new(bytes.Buffer)
	if err := t.ExecuteTemplate(b, "title", nil); err != nil || b.Len() == 0 {
		return defaultTitle
	}
	return b.String()
}
예제 #22
0
파일: scrdkd.go 프로젝트: kushaldas/shonku
/*
Builds a post based on the template
*/
func build_post(ps Post, ptype string) string {
	var doc bytes.Buffer
	var body, name string
	var err error
	var tml *template.Template
	if ptype == "post" {
		tml, err = template.ParseFiles("./templates/post.html", "./templates/base.html")
		name = "./output/posts/" + ps.Slug + ".html"
	} else {
		// This should read the pages template
		tml, err = template.ParseFiles("./templates/page.html", "./templates/base.html")
		name = "./output/pages/" + ps.Slug + ".html"
	}
	err = tml.ExecuteTemplate(&doc, "base", ps)
	if err != nil {
		fmt.Println("Error executing template: ", err)
	}
	body = doc.String()

	f, err := os.Create(name)
	defer f.Close()
	n, err := io.WriteString(f, body)

	if err != nil {
		fmt.Println("Error while writing output: ", n, err)
	}

	return body
}
예제 #23
0
func (tl *TemplateLoader) loadTemplates(searchPath string, includeTmpl *template.Template) error {
	tmplFiles, err := filepath.Glob(filepath.Join(tl.basePath, searchPath, "*.tmpl"))
	if err != nil {
		return err
	}

	for _, tf := range tmplFiles {
		tfBytes, err := ioutil.ReadFile(tf)
		if err != nil {
			return err
		}
		tfStr := string(tfBytes)

		tn, err := filepath.Rel(tl.basePath, tf)
		if err != nil {
			return err
		}
		tn = strings.TrimSuffix(tn, ".tmpl")

		// We clone the included templates here to keep each namespace fresh.
		it, err := includeTmpl.Clone()
		if err != nil {
			return err
		}

		t, err := it.New(tn).Parse(tfStr)
		if err != nil {
			return err
		}

		tl.templates[tn] = t
	}

	return nil
}
예제 #24
0
func RegistroPrendaGET(html *template.Template) gin.HandlerFunc {
	return func(c *gin.Context) {
		mapa := MapaInfo{}
		mapa.ObtenerDatosRegistroPrenda()
		html.ExecuteTemplate(c.Writer, "registroPrenda.html", mapa)
	}
}
예제 #25
0
// submitPage is the submission page served on "/submit/"
func submitPage(w http.ResponseWriter, r *http.Request, t *template.Template) {
	if r.Method == "POST" {
		if r.FormValue("title") == "" || r.FormValue("content") == "" {
			http.Redirect(w, r, "/submit/", http.StatusFound)
			return
		}

		newEntry := &blog.BlogEntry{
			Title:   r.FormValue("title"),
			Content: r.FormValue("content"),
			Date:    time.Now(),
		}

		blogState.AddEntry(newEntry)
		sort.Sort(blog.ByDate{blogState.Entries})

		http.Redirect(w, r, "/", http.StatusFound)
	} else {
		err := t.Execute(w, nil)
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
	}
}
예제 #26
0
// ExecTpl is a utility function to execute the template that may be removed shortly in the future.
func ExecTpl(w http.ResponseWriter, tpl *template.Template, data interface{}) {
	err := tpl.Execute(w, data)
	if err != nil {
		w.Write([]byte("Error executing template: " + err.Error()))
	}
	return
}
예제 #27
0
파일: config.go 프로젝트: jmheidly/dex
func findTemplate(name string, tpls *template.Template) (*template.Template, error) {
	tpl := tpls.Lookup(name)
	if tpl == nil {
		return nil, fmt.Errorf("unable to find template: %q", name)
	}
	return tpl, nil
}
예제 #28
0
파일: context.go 프로젝트: NeoChow/qor
func (context *Context) Execute(name string, result interface{}) {
	var tmpl *template.Template
	var cacheKey string

	if context.Action == "" {
		context.Action = name
	}

	if context.Resource != nil {
		cacheKey = path.Join(context.resourcePath(), name)
	} else {
		cacheKey = name
	}

	if t, ok := templates[cacheKey]; !ok || true {
		var err error
		tmpl = template.New("layout.tmpl").Funcs(context.FuncMap())
		if tmpl, err = context.FindTemplate(tmpl, "layout.tmpl"); err == nil {
			for _, name := range []string{"header", "footer"} {
				if tmpl.Lookup(name) == nil {
					tmpl, _ = context.FindTemplate(tmpl, name+".tmpl")
				}
			}
		}
	} else {
		tmpl = t
	}

	context.Content = context.Render(name, result)
	if err := tmpl.Execute(context.Writer, context); err != nil {
		fmt.Println(err)
	}
}
예제 #29
0
파일: camweb.go 프로젝트: robryk/camlistore
func applyTemplate(t *template.Template, name string, data interface{}) []byte {
	var buf bytes.Buffer
	if err := t.Execute(&buf, data); err != nil {
		log.Printf("%s.Execute: %s", name, err)
	}
	return buf.Bytes()
}
예제 #30
0
파일: tmpl.go 프로젝트: cagnosolutions/webc
func (ts *TemplateStore) Render(w http.ResponseWriter, name string, data Model) {
	var tmpl *template.Template
	if ts.Development {
		includes, err := filepath.Glob(ts.TemplateDir + "includes/*.tmpl")
		if err != nil {
			log.Fatal(err)
		}
		files := append(includes, ts.TemplateDir+"layouts/"+name)
		tmpl = template.Must(template.New("func").Funcs(ts.funcs).ParseFiles(files...))
	} else {
		var ok bool
		ts.RLock()
		tmpl, ok = ts.templates[name]
		ts.RUnlock()
		if !ok {
			http.Error(w, "404. Page not found", 404)
			return
		}
	}

	buf := ts.bufpool.get()
	defer ts.bufpool.reset(buf)

	err := tmpl.ExecuteTemplate(buf, "base", data)
	if err != nil {
		log.Println(err)
		http.Error(w, "500. Internal server error", 500)
		return
	}

	w.Header().Set("Content-Type", "text/html; charset=utf-8")
	buf.WriteTo(w)
	return
}