Golang html/template.ParseFiles function examples

package html/template

ParseFiles creates a new Template and parses the template definitions from the named files. The returned template's name will have the (base) name and (parsed) contents of the first file. There must be at least one file. If an error occurs, parsing stops and the returned *Template is nil.

Golang html/template.ParseFiles function usage examples

Example 1:

 var templates = template.Must(template.ParseFiles(
  "header.html",
  "index.html",
  "apps/types.html",
  "music.html", "tmpl/snips.tmpl",
  "footer.html"))

Example 2:

 templateDir := sp.config.templateDir // var templateDir string

 tmpl, err := template.ParseFiles(templateDir+"/main.tpl", templateDir+"/body_"+sp.error.computedStatus+".tpl")
 if err != nil {
 http.Error(w, "Unable to serve page : "+sp.error.computedStatus, code)
 return
 }

Example 3:

 package main

 import (
 "fmt"
 "html/template"
 "os"
 )

 func main() {

 t := template.New("HELLO")

 var templates = template.Must(t.ParseFiles("defaultTemplate.html"))

 data := map[string]interface{}{
 "Title": "Hello World!",
 }

 templates.ExecuteTemplate(os.Stdout, "defaultTemplate.html", data)

 fmt.Println("\n\n")

 fmt.Println("Template name is : ", t.Name())

 }

content of defaultTemplate.html

 <!DOCTYPE html>
 <html lang="en">
 <head>
 <title>{{ .Title }}</title>
 </head>

Output :

 <!DOCTYPE html>
 <html lang="en">
 <head>
 <title>Hello World!</title>
 </head>

Template name is : HELLO

References :

http://golang.org/pkg/html/template/#ParseFiles

https://github.com/aclissold/andrewclissold.appspot.com/blob/master/app.go

https://github.com/arkenio/gogeta/blob/master/status.go

Advertisement