示例#1
0
func compile(options Options) *template.Template {
	dir := options.Directory
	t := template.New(dir)
	t.Delims(options.Delims.Left, options.Delims.Right)
	// parse an initial template in case we don't have any
	template.Must(t.Parse("Macaron"))

	funcMap := template.FuncMap{}
	// add our funcmaps
	for _, funcs := range options.Funcs {
		for k, v := range funcs {
			funcMap[k] = v
		}
	}

	filepath.Walk(dir, func(path string, info os.FileInfo, err error) error {
		r, err := filepath.Rel(dir, path)
		if err != nil {
			return err
		}

		ext := filepath.Ext(r)
		for _, extension := range options.Extensions {
			if ext == extension {
				name := (r[0 : len(r)-len(ext)])

				tmpl, err := gojade.CompileFile(path, gojade.Options{
					Funcs: funcMap,
				})

				if err != nil {
					panic(err)
				}

				t.Funcs(funcMap)
				t.AddParseTree(filepath.ToSlash(name), tmpl.Tree)

				break
			}
		}

		return nil
	})

	return t
}
示例#2
0
func NewScriptHandler(script string, contentType string) func(*macaron.Context) {
	ext := filepath.Ext(script)
	return func(ctx *macaron.Context) {
		var err error
		var output []byte
		errquit := func(err error) {
			ctx.Error(500, err.Error()+"\n"+string(output))
			return
		}
		switch ext {
		case ".sh":
			output, err = runShellScript(ctx, script)
			render(ctx, output, err, contentType)
		case ".html":
			output, err = ioutil.ReadFile(script)
			render(ctx, output, err, contentType)
		case ".md":
			output, err = ioutil.ReadFile(script)
			if err != nil {
				errquit(err)
				return
			}
			unsafe := blackfriday.MarkdownCommon(output)
			html := bluemonday.UGCPolicy().SanitizeBytes(unsafe)
			render(ctx, html, nil, "html")
		case ".jade":
			tmpl, err := jade.CompileFile(script, jade.Options{})
			if err != nil {
				errquit(err)
				return
			}
			buf := bytes.NewBuffer(nil)
			err = tmpl.Execute(buf, nil)
			render(ctx, buf.Bytes(), err, "html")
		default:
			log.Warn("Unknown script ext", script, ext)
			output, err = ioutil.ReadFile(script)
			render(ctx, output, err, detectCType(script))
		}
	}
}