本文整理汇总了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)
}
}
示例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)
}
示例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
}
示例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)
}
}
示例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
}
示例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
}
示例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
}
示例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
}
示例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)
}
}
示例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)
}
}
示例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
}
示例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)
}
}
示例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)
}
}
示例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
}
示例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,
})
}