当前位置: 首页>>代码示例>>Golang>>正文


Golang template.Template类代码示例

本文整理汇总了Golang中html/template.Template的典型用法代码示例。如果您正苦于以下问题:Golang Template类的具体用法?Golang Template怎么用?Golang Template使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了Template类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。

示例1: BulkHandler

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)

	}

}
开发者ID:Ryman,项目名称:check,代码行数:29,代码来源:handlers.go

示例2: renderHTML

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)
}
开发者ID:mommel,项目名称:eremetic,代码行数:25,代码来源:handler.go

示例3: notFound

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
}
开发者ID:rawbite,项目名称:devd,代码行数:7,代码来源:fileserver.go

示例4: loadTemplate

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)
	}
}
开发者ID:timtadh,项目名称:cc-survey,代码行数:7,代码来源:views.go

示例5: getTemplateInstance

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

}
开发者ID:Lao-liu,项目名称:GoInk,代码行数:28,代码来源:view.go

示例6: ParseGlob

// 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
}
开发者ID:sunfmin,项目名称:mangotemplate,代码行数:27,代码来源:template.go

示例7: InitBlog

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
}
开发者ID:joelgwebber,项目名称:j15r.com,代码行数:34,代码来源:blog.go

示例8: ErrorAccessingPage

// 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
}
开发者ID:2722,项目名称:lantern,代码行数:34,代码来源:status.go

示例9: renderTemplate

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)
	}
}
开发者ID:patrickjr,项目名称:poker2,代码行数:7,代码来源:users.go

示例10: actionCategories

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)
	}
}
开发者ID:DeyV,项目名称:go-newsagg,代码行数:25,代码来源:actions.go

示例11: Apply

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
}
开发者ID:sore0159,项目名称:golang-helpers,代码行数:7,代码来源:handler.go

示例12: actionCategoryList

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)
	}
}
开发者ID:DeyV,项目名称:go-newsagg,代码行数:35,代码来源:actions.go

示例13: actionHome

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)
	}
}
开发者ID:DeyV,项目名称:go-newsagg,代码行数:26,代码来源:actions.go

示例14: LoadPartialTemplates

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
}
开发者ID:fblecha,项目名称:fuel,代码行数:29,代码来源:template_helpers.go

示例15: dirList

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,
	})
}
开发者ID:twocool,项目名称:srvdir,代码行数:27,代码来源:fs.go


注:本文中的html/template.Template类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。