Skip to content

Instantly share code, notes, and snippets.

@Komosa
Created March 7, 2017 00:19
Show Gist options
  • Save Komosa/8507448f7e3f8db81e7939e259f06091 to your computer and use it in GitHub Desktop.
Save Komosa/8507448f7e3f8db81e7939e259f06091 to your computer and use it in GitHub Desktop.
htmlize
package main
import (
"errors"
"fmt"
"html/template"
"io"
"os"
"strings"
)
type Meta struct {
Analytics string // google analytics id, could be empty
Disqus string // disqus id, could be empty
Title string // title of current article
Prev, Next string // titles of prev and next articles, should HrefFor() to articles, could be empty
Tags []string // list of tags, should HrefFor() to post listings
HrefFor func(string) string // translate title or tag into URL
}
func (meta Meta) Htmlize(content io.Reader, out io.Writer) error {
if meta.HrefFor == nil {
return errors.New(`Meta.HrefFor() is nil`)
}
err := template.Must(template.New("header").Parse(Header)).Execute(out, meta)
if err != nil {
return err
}
_, err = io.Copy(out, content)
if err != nil {
return err
}
return template.Must(template.New("nav").Funcs(map[string]interface{}{"hreffor": meta.HrefFor}).
Parse(Footer)).Execute(out, meta)
}
func run() error {
return Meta{
Title: "example blog post",
HrefFor: func(title string) string { return strings.Replace(title, " ", "-", -1) },
Tags: []string{"t1", "hasztag dwa"},
}.Htmlize(strings.NewReader(`<h1>foo</h1>bar`), os.Stdout)
}
func main() {
err := run()
if err == nil {
return
}
fmt.Fprintf(os.Stderr, "%s\n", err)
os.Exit(1)
}
//~ `UA-92786202-1`
//~ pkomosa
const Header = `<!DOCTYPE html><html lang=pl><head><meta charset=utf-8><meta name=viewport content="width=device-width,initial-scale=1">
<title>{{.Title}}</title>
<style>img{max-width:100%;height:auto}pre{max-width:100%;height:auto;white-space:pre-wrap}.navi href{flex-grow:1}
.navi{display:flex;flex-direction:row;justify-content:space-between;padding-bottom:.5em;font-style:italic}</style>
{{with .Analytics}}<script> window.ga=window.ga||function(){(ga.q=ga.q||[]).push(arguments)};
ga.l=+new Date; ga('create', '{{.}}', 'auto'); ga('send', 'pageview'); </script>
<script async src='//www.google-analytics.com/analytics.js'></script>{{end}}
{{with .Disqus}}<script async src='//{{.}}.disqus.com/embed.js>'</script>{{end}}
</head><body><strong>{{.Title}}</strong><hr>
`
const Footer = `<hr>{{if or .Prev .Next}}<div class=navi>
{{with .Prev}}<a href={{hreffor .}}>← {{.}}</a>{{end}}
{{with .Next}}<a href={{hreffor .}}>{{.}} →</a>{{end}}
</div>{{end}}
{{with .Tags}}<footer><div class=navi>
{{range .}}<a href={{hreffor .}}>#{{.}}</a>{{end}}
</footer></div>{{end}}
`
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment