Ejemplo n.º 1
0
func writeTmpl(tmpl *template.Template, vmConfigs []vm) {
	file, err := os.Create(tmpl.Name())
	checkError(err)
	defer file.Close()
	err = tmpl.Execute(file, vmConfigs)
	checkError(err)
}
Ejemplo n.º 2
0
func (t *Repository) addDependencies(templ *template.Template) (*template.Template, error) {

	name := templ.Name()

	deps := t.flattenDependencies(templ, nil)

	for dep := range deps {

		if dep == "" {
			continue
		}

		tt := templ.Lookup(dep)

		// Check if we have it
		if tt == nil {
			tt = t.templates[dep]

			// Still dont have it return an error
			if tt == nil {
				return templ, fmt.Errorf("Could not find template %s", dep)
			}
			var err error

			// Add it to the parse tree
			templ, err = templ.AddParseTree(dep, tt.Tree)

			if err != nil {
				return templ, fmt.Errorf("Dependency Error: %v", err)
			}

		}
	}
	return templ.Lookup(name), nil
}
Ejemplo n.º 3
0
func parseEventListenerTemplates() {
	var templ *template.Template
	eventListenersStore = make(map[string]*template.Template)
	templ = template.Must(template.New("clickEventListener").Parse(clickEventListenerTpl))
	eventListenersStore[templ.Name()] = templ
	templ = template.Must(template.New("submitEventListener").Parse(submitEventListenerTpl))
	eventListenersStore[templ.Name()] = templ
}
Ejemplo n.º 4
0
// applyTemplateToResponseWriter uses an http.ResponseWriter as the io.Writer
// for the call to template.Execute.  It uses an io.Writer wrapper to capture
// errors from the underlying http.ResponseWriter.  Errors are logged only when
// they come from the template processing and not the Writer; this avoid
// polluting log files with error messages due to networking issues, such as
// client disconnects and http HEAD protocol violations.
func applyTemplateToResponseWriter(rw http.ResponseWriter, t *template.Template, data interface{}) {
	w := &writerCapturesErr{w: rw}
	err := t.Execute(w, data)
	// There are some cases where template.Execute does not return an error when
	// rw returns an error, and some where it does.  So check w.err first.
	if w.err == nil && err != nil {
		// Log template errors.
		log.Printf("%s.Execute: %s", t.Name(), err)
	}
}
Ejemplo n.º 5
0
func (s *server) listHandler(t *template.Template) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		if err := t.Execute(w, s); err != nil {
			log.Printf("error executing template %s: %v", t.Name(), err)
			w.WriteHeader(500)
			w.Write([]byte(err.Error()))
			return
		}
	}
}
Ejemplo n.º 6
0
func renderTemplate(w http.ResponseWriter, tmpl *template.Template, data interface{}) error {
	wr := &writeRecorder{w: w}
	if err := tmpl.Execute(wr, data); err != nil {
		if !wr.wrote {
			// TODO(ericchiang): replace with better internal server error.
			http.Error(w, "Internal server error", http.StatusInternalServerError)
		}
		return fmt.Errorf("Error rendering template %s: %s", tmpl.Name(), err)
	}
	return nil
}
Ejemplo n.º 7
0
func renderCode(fullpath string, tmpl *template.Template, context interface{}) (fb []byte, err error) {
	targetBuf := bytes.Buffer{}

	err = tmpl.Execute(&targetBuf, context)
	if err != nil {
		return nil, fmt.Errorf("Problem rendering %s : %v", tmpl.Name(), err)
	}

	fb, err = imports.Process(fullpath, targetBuf.Bytes(), nil)
	if err != nil {
		return targetBuf.Bytes(), fmt.Errorf("Problem formatting %s : %v\n%s", tmpl.Name(), err, targetBuf.Bytes())
	}

	return fb, err
}
Ejemplo n.º 8
0
// Parse parses declared templates.
func Parse(t *template.Template) (*template.Template, error) {
	for name, s := range templates {
		var tmpl *template.Template
		if t == nil {
			t = template.New(name)
		}
		if name == t.Name() {
			tmpl = t
		} else {
			tmpl = t.New(name)
		}
		if _, err := tmpl.Parse(s); err != nil {
			return nil, err
		}
	}
	return t, nil
}
Ejemplo n.º 9
0
// computeOutCtx takes a template and its start context and computes the output
// context while storing any inferences in e.
func (e *escaper) computeOutCtx(c context, t *template.Template) context {
	// Propagate context over the body.
	c1, ok := e.escapeTemplateBody(c, t)
	if !ok {
		// Look for a fixed point by assuming c1 as the output context.
		if c2, ok2 := e.escapeTemplateBody(c1, t); ok2 {
			c1, ok = c2, true
		}
		// Use c1 as the error context if neither assumption worked.
	}
	if !ok && c1.state != stateError {
		return context{
			state: stateError,
			// TODO: Find the first node with a line in t.text.Tree.Root
			err: errorf(ErrOutputContext, 0, "cannot compute output context for template %s", t.Name()),
		}
	}
	return c1
}
Ejemplo n.º 10
0
func lazyInitTemplate() {
	webPanelTpl = template.New("")
	var tpl *template.Template
	// main
	tpl = template.Must(template.New("main").Parse(_TPL_PAGE_MAIN))
	webPanelTpl.AddParseTree(tpl.Name(), tpl.Tree)
	webPanelBuilder[tpl.Name()] = buildMainPageData
	// 404
	tpl = template.Must(template.New("404").Parse(_TPL_PAGE_404))
	webPanelTpl.AddParseTree(tpl.Name(), tpl.Tree)
	webPanelBuilder[tpl.Name()] = build404PageData
}
Ejemplo n.º 11
0
// escapeTemplateBody escapes the given template assuming the given output
// context, and returns the best guess at the output context and whether the
// assumption was correct.
func (e *escaper) escapeTemplateBody(c context, t *template.Template) (context, bool) {
	filter := func(e1 *escaper, c1 context) bool {
		if c1.state == stateError {
			// Do not update the input escaper, e.
			return false
		}
		if !e1.called[t.Name()] {
			// If t is not recursively called, then c1 is an
			// accurate output context.
			return true
		}
		// c1 is accurate if it matches our assumed output context.
		return c.eq(c1)
	}
	// We need to assume an output context so that recursive template calls
	// take the fast path out of escapeTree instead of infinitely recursing.
	// Naively assuming that the input context is the same as the output
	// works >90% of the time.
	e.output[t.Name()] = c
	return e.escapeListConditionally(c, t.Tree.Root, filter)
}
Ejemplo n.º 12
0
//Load templates
func init() {
	// Templates = &tst.Trie{}
	var templ *tpl.Template
	Templates = make(map[string]*tpl.Template)
	newTpl = tpl.Must(tpl.New("new.tpl").Parse(newTplString))
	Templates[newTpl.Name()] = newTpl
	editTpl = tpl.Must(tpl.New("edit.tpl").Parse(editTplString))
	Templates[editTpl.Name()] = editTpl
	viewTpl = tpl.Must(tpl.New("view.tpl").Parse(viewTplString))
	Templates[viewTpl.Name()] = viewTpl
	templ = tpl.Must(tpl.New("select.tpl").Parse(selectTplString))
	Templates[templ.Name()] = templ
	templ = tpl.Must(tpl.New("inputText.tpl").Parse(inputTextTplString))
	Templates[templ.Name()] = templ
	templ = tpl.Must(tpl.New("fieldset.tpl").Parse("<fieldset>{{.MAP.Content}}</fieldset>"))
	Templates[templ.Name()] = templ
	templ = tpl.Must(tpl.New("message.tpl").Parse(`<li class="{{.TYPE.Type}}">{{.TYPE.Text}}</li>`))
	Templates[templ.Name()] = templ
	templ = tpl.Must(tpl.New("messagePanel.tpl").Parse(`<ul id="message" class="panel no-bullet">{{.MAP.Content}}</ul>`))
	Templates[templ.Name()] = templ

}
Ejemplo n.º 13
0
//loadTemplate 加载解析模板
func (d *dynamic) loadTemplate(currDir string) (*template.Template, error) {
	if len(d.Template) == 0 {
		return nil, fmt.Errorf(ErrorPageNotTemplate)
	}
	var (
		t                           *template.Template = nil
		filePath, fileName, content string
		b                           []byte
		err                         error
	)

	for _, filename := range d.Template {
		filePath = filepath.Join(currDir, filename)
		fileName = filepath.Base(filename)

		b, err = ioutil.ReadFile(filePath)
		if err != nil {
			return nil, err
		}
		content = d.formatTemplate(string(b))

		var tmpl *template.Template
		if t == nil {
			t = template.New(fileName)
		}
		if fileName == t.Name() {
			tmpl = t
		} else {
			tmpl = t.New(fileName)
		}
		tmpl.Delims(d.Delims.Left, d.Delims.Right)
		tmpl.Funcs(TemplateFuncMap)
		_, err = tmpl.Parse(content)
		if err != nil {
			return nil, err
		}
	}
	return t, nil
}
Ejemplo n.º 14
0
// runTemplateCommand executes the given template with the given data,
// which generates a command to execute. If exitNonZeroOK is true, no
// error is returned if the exit code is not 0, otherwise an error is
// returned.
func runTemplateCommand(t *template.Template, exitNonZeroOK bool, data interface{}) (
	exitCode int, err error,
) {
	// Clone the template to ensure the original won't be changed.
	cloned, err := t.Clone()
	if err != nil {
		return -1, errors.Annotatef(err, "cannot clone command template %q", t.Name())
	}
	var buf bytes.Buffer
	if err := cloned.Execute(&buf, data); err != nil {
		return -1, errors.Annotatef(err, "cannot execute command template %q", t.Name())
	}
	command := buf.String()
	logger.Debugf("running command %q", command)
	result, err := exec.RunCommands(exec.RunParams{Commands: command})
	if err != nil {
		return -1, errors.Annotatef(err, "cannot run command %q", command)
	}
	exitCode = result.Code
	stdout := string(result.Stdout)
	stderr := string(result.Stderr)
	logger.Debugf(
		"command %q returned code=%d, stdout=%q, stderr=%q",
		command, exitCode, stdout, stderr,
	)
	if exitCode != 0 {
		if exitNonZeroOK {
			return exitCode, nil
		}
		return exitCode, errors.Errorf(
			"command %q failed with exit code %d",
			command, exitCode,
		)
	}
	return 0, nil
}
Ejemplo n.º 15
0
func renderTemplate(t *template.Template, o *renderOption, w io.Writer) error {
	return t.ExecuteTemplate(w, t.Name(), o)
}