forked from shaoshing/train
-
Notifications
You must be signed in to change notification settings - Fork 0
/
helpers.go
66 lines (55 loc) · 1.64 KB
/
helpers.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
package train
import (
"fmt"
"html/template"
"os"
"path"
"strconv"
"strings"
"time"
)
type Helpers struct{}
const (
JavascriptTag = `<script src="%s"%s></script>`
StylesheetTag = `<link type="text/css" rel="stylesheet" href="%s"%s>`
)
func (this Helpers) JavascriptTag(name string) template.HTML {
assetUrl := "javascripts/" + name + ".js"
paths, mtimes := resolveAssetUrls(assetUrl)
return generateRawHtml(paths, "", mtimes, JavascriptTag)
}
func (this Helpers) StylesheetTagWithParam(name string, param string) template.HTML {
assetUrl := "stylesheets/" + name + ".css"
paths, mtimes := resolveAssetUrls(assetUrl)
return generateRawHtml(paths, param, mtimes, StylesheetTag)
}
func (this Helpers) StylesheetTag(name string) template.HTML {
return this.StylesheetTagWithParam(name, "")
}
func resolveAssetUrls(assetUrl string) (urls []string, mtimes []time.Time) {
paths, err := ReadAssetsFunc(assetUrl, func(filePath string, content string) {})
if err != nil {
panic(err)
}
if Config.BundleAssets {
paths = paths[len(paths)-1:]
}
for _, assetPath := range paths {
info, _ := os.Stat(assetPath)
mtimes = append(mtimes, info.ModTime())
assetUrl := path.Clean(strings.Replace(assetPath, Config.AssetsPath, Config.AssetsUrl, 1))
urls = append(urls, assetUrl)
}
return
}
func generateRawHtml(urls []string, param string, mtimes []time.Time, tag string) template.HTML {
htmls := []string{}
if len(param) != 0 {
param = " " + param
}
for i, url := range urls {
murl := url + "?" + strconv.FormatInt(mtimes[i].Unix(), 10)
htmls = append(htmls, fmt.Sprintf(tag, murl, param))
}
return template.HTML(strings.Join(htmls, "\n"))
}