File: compile.go

package info (click to toggle)
golang-github-yosssi-ace 0.0.4%2Bgit20160102.51.71afeb7-1
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 468 kB
  • ctags: 249
  • sloc: makefile: 3; sh: 1
file content (107 lines) | stat: -rw-r--r-- 2,261 bytes parent folder | download | duplicates (3)
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
package ace

import (
	"bytes"
	"fmt"
	"html/template"
)

// Actions
const (
	actionDefine               = `%sdefine "%s"%s`
	actionEnd                  = "%send%s"
	actionTemplate             = `%stemplate "%s"%s`
	actionTemplateWithPipeline = `%stemplate "%s" %s%s`
)

// PreDefinedFuncs
const (
	preDefinedFuncNameHTML = "HTML"
)

// CompileResult compiles the parsed result to the template.Template.
func CompileResult(name string, rslt *result, opts *Options) (*template.Template, error) {
	// Initialize the options.
	opts = InitializeOptions(opts)

	// Create a template.
	t := template.New(name)

	return CompileResultWithTemplate(t, rslt, opts)
}

// CompileResultWithTemplate compiles the parsed result and associates it with t.
func CompileResultWithTemplate(t *template.Template, rslt *result, opts *Options) (*template.Template, error) {
	// Initialize the options.
	opts = InitializeOptions(opts)

	var err error

	// Create a buffer.
	baseBf := bytes.NewBuffer(nil)
	innerBf := bytes.NewBuffer(nil)
	includeBfs := make(map[string]*bytes.Buffer)

	// Write data to the buffer.
	for _, e := range rslt.base {
		if _, err := e.WriteTo(baseBf); err != nil {
			return nil, err
		}
	}

	for _, e := range rslt.inner {
		if _, err = e.WriteTo(innerBf); err != nil {
			return nil, err
		}
	}

	for path, elements := range rslt.includes {
		bf := bytes.NewBuffer(nil)

		// Write a define action.
		bf.WriteString(fmt.Sprintf(actionDefine, opts.DelimLeft, path, opts.DelimRight))

		for _, e := range elements {
			if _, err = e.WriteTo(bf); err != nil {
				return nil, err
			}
		}

		// Write an end action.
		bf.WriteString(fmt.Sprintf(actionEnd, opts.DelimLeft, opts.DelimRight))

		includeBfs[path] = bf
	}

	// Set Delimiters.
	t.Delims(opts.DelimLeft, opts.DelimRight)

	// Set FuncMaps.
	t.Funcs(template.FuncMap{
		preDefinedFuncNameHTML: func(s string) template.HTML {
			return template.HTML(s)
		},
	})

	t.Funcs(opts.FuncMap)

	// Parse a string to the template.
	t, err = t.Parse(baseBf.String())
	if err != nil {
		return nil, err
	}

	t, err = t.Parse(innerBf.String())
	if err != nil {
		return nil, err
	}

	for _, bf := range includeBfs {
		t, err = t.Parse(bf.String())
		if err != nil {
			return nil, err
		}
	}

	return t, nil
}