當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。