Created
August 10, 2015 07:32
-
-
Save egonelbre/988b6b5241ab577f8eb3 to your computer and use it in GitHub Desktop.
html/template example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<link rel="stylesheet" type="text/css" href="main.css"> | |
<link rel="stylesheet" type="text/css" href="main.js"> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!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> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{{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