Skip to content

Instantly share code, notes, and snippets.

@egonelbre
Created August 10, 2015 07:32
Show Gist options
  • Save egonelbre/988b6b5241ab577f8eb3 to your computer and use it in GitHub Desktop.
Save egonelbre/988b6b5241ab577f8eb3 to your computer and use it in GitHub Desktop.
html/template example
<link rel="stylesheet" type="text/css" href="main.css">
<link rel="stylesheet" type="text/css" href="main.js">
<!DOCTYPE html>
<html>
<head>
<title>Example</title>
{{ template "include.html" . }}
</head>
<body>
<h1>Example</h1>
<div class="content">
{{ template "posts.html" .Posts }}
</div>
</body>
</html>
package main
import (
"html/template"
"os"
)
func check(err error) {
if err != nil {
panic(err)
}
}
type Post struct {
Name string
Desc string
}
func main() {
T, err := template.ParseGlob("*.html")
check(err)
posts := []Post{
{"Alpha", "Hello"},
{"Beta", "World"},
}
err = T.ExecuteTemplate(os.Stdout, "index.html", map[string]interface{}{
"Posts": posts,
})
check(err)
}
{{define "Post"}}
<div class="post">
<h2>{{.Name}}</h2>
<div>{{.Desc}}</div>
</div>
{{end}}
<div class="major-posts">
{{range . }}
{{template "Post" . }}
{{end}}
</div>
<div class="minor-posts">
<!-- alternative syntax for range -->
{{range $post := . }}
{{template "Post" $post }}
{{end}}
</div>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment