1
0
mirror of https://github.com/danog/gojekyll.git synced 2024-12-12 11:17:19 +01:00
gojekyll/plugins/avatar.go

72 lines
1.9 KiB
Go
Raw Normal View History

2017-07-01 15:38:16 +02:00
package plugins
import (
2017-07-20 18:26:47 +02:00
"bytes"
2017-07-01 15:38:16 +02:00
"fmt"
2017-07-20 18:26:47 +02:00
"hash/crc32"
2017-07-01 15:38:16 +02:00
"strings"
2017-07-20 18:26:47 +02:00
"text/template"
2017-07-01 15:38:16 +02:00
"github.com/danog/gojekyll/tags"
"github.com/danog/liquid"
"github.com/danog/liquid/render"
2017-07-01 15:38:16 +02:00
)
func init() {
2017-07-09 04:47:50 +02:00
register("jekyll-avatar", jekyllAvatarPlugin{})
}
type jekyllAvatarPlugin struct{ plugin }
func (p jekyllAvatarPlugin) ConfigureTemplateEngine(e *liquid.Engine) error {
2017-07-09 04:47:50 +02:00
e.RegisterTag("avatar", avatarTag)
return nil
2017-07-01 15:38:16 +02:00
}
2017-07-20 18:26:47 +02:00
var avatarTemplate = template.Must(template.New("avatar").Parse(strings.TrimSpace(`
<img class="avatar avatar-small" src="https://{{.Subdomain}}.githubusercontent.com/{{.User}}?v=3&amp;s={{.Size}}" alt="{{.User}}" srcset="https://{{.Subdomain}}.githubusercontent.com/{{.User}}?v=3&amp;s={{.Size}} 1x, https://{{.Subdomain}}.githubusercontent.com/{{.User}}?v=3&amp;s=80 2x, https://{{.Subdomain}}.githubusercontent.com/{{.User}}?v=3&amp;s=120 3x, https://{{.Subdomain}}.githubusercontent.com/{{.User}}?v=3&amp;s=160 4x" width="{{.Size}}" height="{{.Size}}" data-proofer-ignore="true" />
`)))
2017-07-01 15:38:16 +02:00
2017-07-04 23:13:47 +02:00
func avatarTag(ctx render.Context) (string, error) {
2017-07-01 16:37:11 +02:00
var (
user string
size interface{} = 40
)
2017-07-06 05:26:47 +02:00
argsline, err := ctx.ExpandTagArg()
2017-07-01 16:37:11 +02:00
if err != nil {
2017-07-04 14:06:34 +02:00
return "", err
2017-07-01 16:37:11 +02:00
}
args, err := tags.ParseArgs(argsline)
if err != nil {
2017-07-04 14:06:34 +02:00
return "", err
2017-07-01 16:37:11 +02:00
}
if len(args.Args) > 0 {
user = args.Args[0]
}
options, err := args.EvalOptions(ctx)
if err != nil {
2017-07-04 14:06:34 +02:00
return "", err
2017-07-01 16:37:11 +02:00
}
for name, value := range options {
switch name {
case "user":
user = fmt.Sprint(value)
case "size":
size = value
default:
2017-07-04 14:06:34 +02:00
return "", fmt.Errorf("unknown avatar argument: %s", name)
2017-07-01 16:37:11 +02:00
}
}
if user == "" {
2017-07-04 14:06:34 +02:00
return "", fmt.Errorf("parse error in avatar tag parameters %s", argsline)
2017-07-01 16:37:11 +02:00
}
2017-07-20 18:26:47 +02:00
n := crc32.Checksum([]byte(fmt.Sprintf("%s:%d", user, size)), crc32.IEEETable) % 4
s := struct {
User, Subdomain string
Size interface{}
}{user, fmt.Sprintf("avatar%d", n), size}
buf := new(bytes.Buffer)
err = avatarTemplate.Execute(buf, s)
return buf.String(), err
2017-07-01 15:38:16 +02:00
}