// ExecuteTemplate executes a template on the source TeX files. func (t *CompileTask) ExecuteTemplate(templ *template.Template, data interface{}, inputFilename string, outputFilename string) { sc := t.context() useTempFile := outputFilename == "" if useTempFile { outputFilename = sc.MustGetTempFile().Name() } inputFilename = sc.AbsPath(t.defaultCompileFilename(inputFilename)) f, err := os.Create(sc.AbsPath(outputFilename)) if err != nil { panic(err) } w := io.Writer(f) err = templ.ExecuteTemplate(w, filepath.Base(inputFilename), data) if err != nil { panic(err) } f.Close() if useTempFile { // copy back, remove temp err = os.Remove(inputFilename) if err != nil { panic(err) } err = sc.CopyFile(outputFilename, inputFilename) if err != nil { panic(err) } } }
func renderTemplate(tmpl *template.Template, name string, data interface{}) string { var buf bytes.Buffer if err := tmpl.ExecuteTemplate(&buf, name, data); err != nil { panic(err) } return buf.String() }
// templateWorker create file from template // done channel send nil or error back func templateWorker(tpl *template.Template, ftpl FileTemplates, done chan error) { // check file template path ok, err := utils.PathExists(ftpl.Path) if err != nil { done <- err return } // file template path not exists, create new file template path if !ok { if err := os.MkdirAll(ftpl.Path, 0755); err != nil { done <- err return } } // create new target file f, err := os.OpenFile(filepath.Join(ftpl.Path, ftpl.Target), os.O_WRONLY|os.O_CREATE, 0755) if err != nil { done <- err return } defer f.Close() // generate file content, // send return to channel (nil or err) done <- tpl.ExecuteTemplate(f, ftpl.Tpl, ftpl.Vars) }
func (r Renderer) RenderPost(pc *PostContext, templates *template.Template) error { err := os.MkdirAll(path.Join(r.OutputPath, pc.Slug), 0755) if err != nil { log.Panicf(err.Error()) } outfile, err := os.Create(path.Join(r.OutputPath, pc.Slug, "index.html")) if err != nil { log.Panicf(err.Error()) } err = templates.ExecuteTemplate(outfile, "post.html", pc) if err != nil { log.Panicf(err.Error()) } // copy images log.Printf("\"%s\": Using %d %s", pc.Slug, len(pc.Images), pluralize("image", len(pc.Images))) for _, image := range pc.Images { err = cp(image.SrcAbsPath, path.Join(r.OutputPath, pc.Slug, image.Filename)) if err != nil { log.Panicf(err.Error()) } } log.Printf("\"%s\": Done rendering", pc.Slug) return nil }
func processFile(fc FileConfig, t *template.Template) { // in file iFile, err := os.Open(fc.Name) if err != nil { panic("Can't open " + fc.Name) } defer iFile.Close() // out file oFile, err := os.Create(fc.Name + "_out.txt") if err != nil { panic("Can't open/write to " + fc.Name + "_out.txt") } defer oFile.Close() r := csv.NewReader(iFile) r.Comma = '\t' r.TrailingComma = true record, err := r.Read() for i := 0; err == nil; record, err = r.Read() { if i == 0 { t.ExecuteTemplate(oFile, fc.TemplateName+"_H", makeTemplateContext(&record)) } i = i + 1 if i <= fc.Skip { continue } oFile.Write([]byte("\n")) t.ExecuteTemplate(oFile, fc.TemplateName, makeTemplateContext(&record)) } fmt.Println(err) oFile.Sync() }
func writeSingleJavaFile(tpl *template.Template, filedir string, javapackage string, templateName string, name string, data interface{}) { jfile, err := os.Create(filepath.Join(filedir, strings.Title(name)+".java")) defer jfile.Close() dieIf(err) fmt.Fprintf(jfile, "package %s;\n\n", javapackage) err = tpl.ExecuteTemplate(jfile, templateName, data) dieIf(err) }
func (sb *StringBuilder) AddTemplate(t *template.Template, name string, data interface{}) error { buf := &bytes.Buffer{} err := t.ExecuteTemplate(buf, name, data) if err != nil { return err } sb.Append(buf.String()) return nil }
// ExecuteTemplateAndWrite executes the template and writes the buffer to dst. func (i *Invoice) ExecuteTemplateAndWrite(t *template.Template, name, dst string) error { buf := &bytes.Buffer{} if err := t.ExecuteTemplate(buf, name, i); err != nil { return err } if err := ioutil.WriteFile(dst, buf.Bytes(), 0664); err != nil { return err } return nil }
func implementAll(def ObjectDefinition, face *BaseInfo, code *bytes.Buffer, tmpl *template.Template) { impl := face.GetObjectDefinition() impl.ObjectName = def.ObjectName err := tmpl.ExecuteTemplate(code, "object-implement", impl) if err != nil { fmt.Println(err.Error()) } if hasParent(face) { implementAll(def, face.GetParent(), code, tmpl) } }
func renderTemplate(w http.ResponseWriter, tmpl string) { var templates *template.Template if config.liveTemplates { templates = compileTemplates() } else { templates = precompiledTemplates } err := templates.ExecuteTemplate(w, tmpl+".html", nil) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) } }
func NewTestHTMLObjectFieldsFn(t *testing.T, tplate *template.Template, w io.Writer) func() string { return func() string { field := Field{Name: "FieldName", Class: Class{Name: "Class_Name", Project: Project{Name: "ProjectName"}}} for _, tname := range fldtplates { if err := tplate.ExecuteTemplate(w, tname, field); err != nil { fmt.Println(err.Error()) t.Fail() } } return "" } }
func writeTableCrud(w io.Writer, templates *template.Template, pkgName string, table Table) error { return templates.ExecuteTemplate(w, "row", struct { PkgName string TableName string StructName string Columns []Column PrimaryKeyColumns []*Column }{ PkgName: pkgName, TableName: table.TableName, StructName: table.StructName, Columns: table.Columns, PrimaryKeyColumns: table.PrimaryKeyColumns, }) }
func Render(path string, w http.ResponseWriter, r *http.Request, ViewData map[string]interface{}) { w.Header().Add("Content-Type", "text/html;charset=utf-8") w.Header().Add("Server", "iron") var tmpl *template.Template if isTMPLAutoRefresh { tmpl = template.Must(template.New(path).Delims("<?", "?>").ParseFiles(views[path].filenames...)) } else { if nil == views[path].tmpl { views[path].tmpl = template.Must(template.New(path).Delims("<?", "?>").ParseFiles(views[path].filenames...)) } tmpl = views[path].tmpl } tmpl.ExecuteTemplate(w, "frame", ViewData) }
func ProcessEnum(info *BaseInfo, code *bytes.Buffer, tmpl *template.Template) { name := info.GetName() prefix := GetCPrefix(info.GetNamespace()) def := &EnumDefinition{EnumName: name, CType: prefix + name} numValues := info.GetNEnumValues() for i := 0; i < numValues; i++ { value := info.GetEnumValue(i) valDef := EnumValue{Name: CamelCase(value.GetName()), EnumName: name, Value: value.GetValue()} def.Values = append(def.Values, valDef) } err := tmpl.ExecuteTemplate(code, "enum", def) if err != nil { fmt.Println(err.Error()) } }
// alterFuncMap takes the Engine's FuncMap and adds context-specific functions. // // The resulting FuncMap is only valid for the passed-in template. func (e *Engine) alterFuncMap(t *template.Template) template.FuncMap { // Clone the func map because we are adding context-specific functions. var funcMap template.FuncMap = map[string]interface{}{} for k, v := range e.FuncMap { funcMap[k] = v } // Add the 'include' function here so we can close over t. funcMap["include"] = func(name string, data interface{}) string { buf := bytes.NewBuffer(nil) if err := t.ExecuteTemplate(buf, name, data); err != nil { buf.WriteString(err.Error()) } return buf.String() } return funcMap }
// executeTemplateFunc executes the given template in the context of the // parent. If an argument is specified, it will be used as the context instead. // This can be used for nested template definitions. func executeTemplateFunc(t *template.Template) func(string, ...interface{}) (string, error) { return func(s string, data ...interface{}) (string, error) { var dot interface{} switch len(data) { case 0: dot = nil case 1: dot = data[0] default: return "", fmt.Errorf("executeTemplate: wrong number of arguments, expected 1 or 2"+ ", but got %d", len(data)+1) } var b bytes.Buffer if err := t.ExecuteTemplate(&b, s, dot); err != nil { return "", err } return b.String(), nil } }
func processHeader(fc FileConfig, t *template.Template) { // in file iFile, err := os.Open(fc.Name) if err != nil { panic("Can't open " + fc.Name) } defer iFile.Close() r := csv.NewReader(iFile) r.Comma = '\t' r.TrailingComma = true record, err := r.Read() fmt.Println("File: ", fc.Name) w := new(tabwriter.Writer) w.Init(os.Stdout, 0, 8, 0, '\t', tabwriter.Debug) t.ExecuteTemplate(w, fc.TemplateName+"_H", makeTemplateContext(&record)) w.Write([]byte("\n")) t.ExecuteTemplate(w, fc.TemplateName, makeTemplateContext(&record)) w.Flush() fmt.Println("") }
func renderTemplate(viewName string, model interface{}, w http.ResponseWriter, isPartial bool) { var ( t *template.Template err error exists bool ) //Caso não exista o template no cache, vamos prepará-lo if t, exists = templateCache[viewName]; !exists || DebugMode { t = template.New("").Funcs(helpersFuncs) t, err = t.ParseFiles(filepath.Join(TemplatesDir, mainLayoutFile), filepath.Join(TemplatesDir, viewName+".html")) if err != nil { log.Println(err.Error()) InternalError(err, w) return } templateCache[viewName] = t if DebugMode { log.Println(viewName, " compilada") } } w.Header().Set("Content-Type", "text/html") if !isPartial { err = t.ExecuteTemplate(w, "LAYOUT", viewContext{model}) } else { err = t.ExecuteTemplate(w, "MAIN", viewContext{model}) } if err != nil { InternalError(err, w) } }
func GenerateAvailData(client *api.LinodeClient, templates *template.Template, action string, tmpl string, fileDestination string) { data, err := client.CallAction(action) var buf bytes.Buffer if err != nil { return } spec := struct { DATA interface{} }{ nil, } json.Unmarshal(data, &spec) err = templates.ExecuteTemplate(&buf, tmpl, spec) if err != nil { println(err.Error()) } finalSource, err := format.Source(buf.Bytes()) if err != nil { println(err.Error()) return } ioutil.WriteFile(fileDestination, finalSource, 0777) println(string(finalSource)) }
func renderText(c common.Context, templates *template.Template, template string) { if err := templates.ExecuteTemplate(c.Resp, template, c); err != nil { panic(fmt.Errorf("While rendering text: %v", err)) } }
//httpDynamicHandler 处理动态文件 func (ser *Server) httpDynamicHandler(rw http.ResponseWriter, r *http.Request, config *Config, osFile *os.File) { content, err := ioutil.ReadAll(osFile) osFile.Close() if err != nil { //这里以后做error页 http.Error(rw, err.Error(), 500) return } bytesReader := bytes.NewReader(content) //加载配置文件 var dyn dynamic var ( templateTemplate *template.Template fileName string dynamicType []byte b = make([]byte, 1) ) //读取最前一行 L: for { _, err = bytesReader.Read(b) if err != nil { break } switch b[0] { case 13: bytesReader.Read(b) fallthrough case 10: break L default: } dynamicType = append(dynamicType, b...) } //配置,与模板分离 switch string(dynamicType) { case "//config": jsonDecoder := json.NewDecoder(bytesReader) err = jsonDecoder.Decode(&dyn) if err != nil { //这里以后做error页 http.Error(rw, "动态配置文件不正确", 500) return } //转换文件路径 var ( urlURL = r.URL currPath = urlURL.Path currDir = config.RootDirectory + currPath ) for k, v := range config.VirtualDirectory { if strings.HasPrefix(currPath, "/"+k+"/") { currDir = v + strings.TrimPrefix(currPath, "/"+k) break } } //加载模板 fileName = filepath.Base(dyn.Template[0]) templateTemplate, err = dyn.loadTemplate(filepath.Dir(currDir)) if err != nil { //这里以后做error页 http.Error(rw, err.Error(), 500) return } case "//template": //解析模板 fileName = "BW" templateTemplate, err = dyn.parseTemplate(content) if err != nil { //这里以后做error页 http.Error(rw, err.Error(), 500) return } default: http.Error(rw, ErrorPageNotDynamicType, 500) return } var dot = &Dot{ server: ser, config: config, request: r, response: rw, pkg: DotFuncMap, } //执行模板 var ( bytesBuffer = new(bytes.Buffer) ) err = templateTemplate.ExecuteTemplate(bytesBuffer, fileName, dot) if err != nil { //这里以后做error页 http.Error(rw, err.Error(), 500) return } //写入-Body if !dot.tod { bytesBuffer.WriteTo(rw) } }
func render(writer io.Writer, md *Metadata, file string) error { funcMap := template.FuncMap{ "tolower": strings.ToLower, "join": strings.Join, "capitalize": capitalize, "nounderscore": nounderscore, "underscore": inflect.Underscore, "camelize": inflect.Camelize, "camelizedownfirst": inflect.CamelizeDownFirst, "pluralize": inflect.Pluralize, "singularize": inflect.Singularize, "tableize": inflect.Tableize, "typeify": inflect.Typeify, "addacronym": func(a string) string { inflect.AddAcronym(a); return "" }, "addhuman": func(a, b string) string { inflect.AddHuman(a, b); return "" }, "addirregular": func(a, b string) string { inflect.AddIrregular(a, b); return "" }, "addplural": func(a, b string) string { inflect.AddPlural(a, b); return "" }, "addsingular": func(a, b string) string { inflect.AddSingular(a, b); return "" }, "adduncountable": func(a string) string { inflect.AddUncountable(a); return "" }, "add": func(x, y int) int { return x + y }, "sub": func(x, y int) int { return x - y }, "typenull": func(f Field) string { t := f.Type.String() if !strings.HasPrefix(t, "[]") { switch t { case "bool", "float64", "int64", "string": t = "sql.Null" + capitalize(t) default: t = "*" + t } } return t }, "typepointer": func(f Field) string { t := f.Type.String() if !strings.HasPrefix(t, "[]") { t = "*" + t } return t }, } tplName := filepath.Base(file) tpl := template.New("output").Funcs(funcMap) var t *template.Template var err error if file == "" { tplName = "output" t, err = tpl.Parse(default_template) } else { t, err = tpl.ParseFiles(file) } if err != nil { return err } return t.ExecuteTemplate(writer, tplName, md) }
func execTemp(tmpl *template.Template) { tmpl.ExecuteTemplate(os.Stdout, "T3", "data") }
func ProcessObject(info *BaseInfo, code *bytes.Buffer, tmpl *template.Template) { var err error def := info.GetObjectDefinition() // write object definition err = tmpl.ExecuteTemplate(code, "object-definition", def) if err != nil { fmt.Println(err.Error()) } // write interface definition err = tmpl.ExecuteTemplate(code, "interface-definition", def) if err != nil { fmt.Println(err.Error()) } implementAll(def, info, code, tmpl) // object methods numMethods := info.GetNObjectMethods() for i := 0; i < numMethods; i++ { method := info.GetObjectMethod(i) flags := method.GetFunctionFlags() goargs, gorets, cargs, crets := readParams(method, flags) fn := FunctionDefinition{ Name: method.GetName(), Owner: &def, ForGo: ArgsAndRets{Args: goargs, Rets: gorets}, ForC: ArgsAndRets{Args: cargs, Rets: crets}, Flags: flags, Info: method, } var marshal bytes.Buffer for _, param := range cargs { switch param.Dir { case In, InOut: tmpl.ExecuteTemplate(&marshal, "c-marshal", param) case Out: tmpl.ExecuteTemplate(&marshal, "c-decl", param) } } fn.ArgMarshalBody = marshal.String() marshal.Reset() for _, ret := range crets { tmpl.ExecuteTemplate(&marshal, "c-marshal", ret) } fn.RetMarshalBody = marshal.String() tmpl.ExecuteTemplate(code, "go-function", fn) // inherit this method class := info for hasParent(class) { tmp := class.GetObjectDefinition() fn.Owner = &tmp tmpl.ExecuteTemplate(code, "go-function-wrapper", fn) class = class.GetParent() } } }
func main() { log.SetPrefix("pinktxt: ") log.SetFlags(0) var resp = new(compiler.CodeGeneratorResponse) defer func() { output, err := proto.Marshal(resp) if err != nil { log.Fatalf("Error encoding %T: %v", resp, err) return } if resp.Error != nil { log.Printf("Error in response: %s", *resp.Error) } for len(output) > 0 { n, err := os.Stdout.Write(output) if n > len(output) { n = len(output) } output = output[n:] if err != nil { time.Sleep(time.Millisecond * 500) log.Printf("Error writing output to standard out: %v", err) } } }() var req compiler.CodeGeneratorRequest { var input bytes.Buffer if n, err := input.ReadFrom(os.Stdin); err != nil { resp.Error = heapString("error reading from standard input: " + err.Error()) return } else if n == 0 { resp.Error = heapString("no input provided") return } if err := proto.Unmarshal(input.Bytes(), &req); err != nil { resp.Error = heapString("error unmarshalling from standard input: " + err.Error()) return } } params := parseParameters(req.GetParameter()) files := make(map[string]*bytes.Buffer) root := FlatTypeRoot{ Request: &req, Visible: getFlatTypes(&req, false, nil), Exported: getFlatTypes(&req, true, nil), Params: params, HasData: false, ExecParam: nil, } left, right := "(*", "*)" if p := params.Get("left"); len(p) > 0 { left = p } if p := params.Get("right"); len(p) > 0 { right = p } // This code is all awful but at least it gets the job done right now. var tx *template.Template funcs := template.FuncMap{ "find": (typeFinder{root.Request}).Find, "fexec": func(name, outfile string, data ...interface{}) error { subroot := root if len(data) == 1 { d := data[0] if _, ok := d.(FlatTypeRoot); !ok { subroot.ExecParam = d } } else if len(data) > 1 { subroot.ExecParam = data } var out io.Writer = ioutil.Discard if len(name) > 0 { b, ok := files[outfile] if !ok { b = &bytes.Buffer{} files[outfile] = b } out = b subroot.HasData = b.Len() > 0 } if name != "" { return tx.ExecuteTemplate(out, name, subroot) } else { return tx.Execute(out, subroot) } }, "exec": func(name string, dot ...interface{}) (string, error) { var data interface{} = dot if len(dot) == 1 { data = dot[0] } else if len(dot) == 0 { data = nil } var buf bytes.Buffer var err error if name != "" { err = tx.ExecuteTemplate(&buf, name, data) } else { err = tx.Execute(&buf, data) } return buf.String(), err }, } tx = template.New("").Delims(left, right).Funcs(mergeTypeChecks(copyDefaultTemplateFuncs(funcs))) tx, err := tx.ParseFiles(params["template"]...) if err != nil { resp.Error = heapString("error parsing template(s): " + err.Error()) return } templates := params["template"] if tn := params["exec"]; len(tn) > 0 { templates = tn } for _, name := range templates { if err := tx.ExecuteTemplate(ioutil.Discard, name, root); err != nil { resp.Error = heapString(err.Error()) return } } for name, buf := range files { f := &compiler.CodeGeneratorResponse_File{ Name: heapString(name), Content: heapString(buf.String()), } log.Printf("OUT=%q", name) resp.File = append(resp.File, f) } }
func renderTemplate(t *template.Template, o *renderOption, w io.Writer) error { return t.ExecuteTemplate(w, t.Name(), o) }
func (self *HTTPContext) RenderText(templates *template.Template, template string) { if err := templates.ExecuteTemplate(self.Resp(), template, self); err != nil { panic(fmt.Errorf("While rendering text: %v", err)) } }
/* DocHandler will return a handler that renders the documentation for all routes registerd with DocHandle. The resulting func will do this by going through each route in DocumentedRoutes and render the endpoint using the provided template, providing it template functions to render separate endpoints, types, sub types and examples of types. */ func DocHandler(templ *template.Template) http.Handler { return httpcontext.HandlerFunc(func(c httpcontext.HTTPContextLogger) (err error) { c.Resp().Header().Set("Content-Type", "text/html; charset=UTF-8") // we define a func to render a type // it basically just executes the "TypeTemplate" with the provided // stack to avoid infinite recursion renderType := func(t JSONType, stack []string) (result string, err error) { // if the type is already mentioned in one of the parents we have already mentioned, // bail for _, parent := range stack { if parent != "" && parent == t.ReflectType.Name() { result = fmt.Sprintf("[loop protector enabled, render stack: %v]", stack) return } } stack = append(stack, t.ReflectType.Name()) buf := &bytes.Buffer{} // then execute the TypeTemplate with this type and this stack if err = templ.ExecuteTemplate(buf, "TypeTemplate", map[string]interface{}{ "Type": t, "Stack": stack, }); err != nil { return } result = buf.String() return } // routes are documented alphabetically sort.Sort(routes) // define all the functions that we left empty earlier err = templ.Funcs(map[string]interface{}{ "RenderEndpoint": func(r DocumentedRoute) (string, error) { return r.Render(templ.Lookup("EndpointTemplate")) }, "RenderSubType": func(t JSONType, stack []string) (result string, err error) { return renderType(t, stack) }, "RenderType": func(t JSONType) (result string, err error) { return renderType(t, nil) }, "First": first, "Example": func(r JSONType) (result string, err error) { // this will render an example of the provided JSONType defer func() { if e := recover(); e != nil { result = fmt.Sprintf("%v\n%s", e, utils.Stack()) } }() x := utils.Example(r.ReflectType) b, err := json.MarshalIndent(x, "", " ") if err != nil { return } if len(r.Fields) > 0 { var i interface{} if err = json.Unmarshal(b, &i); err != nil { return } if m, ok := i.(map[string]interface{}); ok { newMap := map[string]interface{}{} for k, v := range m { if _, found := r.Fields[k]; found { newMap[k] = v } } if b, err = json.MarshalIndent(newMap, "", " "); err != nil { return } } } result = string(b) return }, }).Execute(c.Resp(), map[string]interface{}{ "Endpoints": routes, }) return }) }
func renderText(w http.ResponseWriter, r *http.Request, templates *textTemplate.Template, template string, data interface{}) { if err := templates.ExecuteTemplate(w, template, data); err != nil { panic(fmt.Errorf("While rendering text: %v", err)) } }