func main () { html_t, err := gaml.GamlToHtml(gaml_template_1) if err != nil { fmt.Printf("error: %s", err.Error()) } template,err := template.New("test_template").Parse(html_t) template.Execute(os.Stdout, "Hello World!") html_t, err = gaml.GamlToHtml(gaml_template_2) if err != nil { fmt.Printf("error: %s", err.Error()) } template,err = template.New("test_template2").Parse(html_t) if err != nil { fmt.Printf("error: %s", err.Error()) } template.Execute(os.Stdout, People) html_t, err = gaml.GamlToHtml(gaml_template_3) if err != nil { fmt.Printf("error: %s", err.Error()) } template,err = template.New("test_template3").Parse(html_t) if err != nil { fmt.Printf("error: %s", err.Error()) } template.Execute(os.Stdout, People) }
func GetTestServer() (*httptest.Server, string) { mux := http.NewServeMux() stormpathMiddleware := NewStormpathMiddleware(mux, nil) mux.Handle("/", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.URL.Path != "/" { http.NotFound(w, r) return } account := stormpathMiddleware.GetAuthenticatedAccount(w, r) w.Header().Add("Content-Type", "text/html") template, err := template.New("main").Parse(mainTemplate) if err != nil { fmt.Fprint(w, err) return } model := map[string]interface{}{ "account": account, "loginUri": Config.LoginURI, "logoutUri": Config.LogoutURI, } if account != nil { model["name"] = account.GivenName } template.Execute(w, model) })) return httptest.NewServer(stormpathMiddleware), stormpathMiddleware.Application.Href }
func (s *SmtpServer) SendEmail(email Email) error { parameters := &struct { From string To string Subject string Message string }{ email.From, strings.Join([]string(email.To), ","), email.Title, email.Message, } buffer := new(bytes.Buffer) template := template.Must(template.New("emailTemplate").Parse(emailTemplate)) template.Execute(buffer, parameters) auth := smtp.PlainAuth("", s.Username, s.Passwd, s.Host) err := smtp.SendMail( fmt.Sprintf("%s:%d", s.Host, s.Port), auth, email.From, email.To, buffer.Bytes()) return err }
func NewContratoStatus(rw http.ResponseWriter, r *http.Request) { query := r.URL.Query() inq_id := getParamToInt(query, "inquilino") imovel_id := getParamToInt(query, "imovel") fmt.Println(inq_id, imovel_id) imovel := model.Db.SelectImovelById(imovel_id) inq := model.Db.SelectInquilinoById(inq_id) new_contrato := structs.Contrato{ Data: query["data"][0], Email: query["email"][0], Prazo_locacao: query["prazo_locacao"][0], Inicio_contrato: query["inicio_contrato"][0], Fim_contrato: query["fim_contrato"][0], Valor_aluguel: query["valor_aluguel"][0], Dia_vencimento: query["dia_vencimento"][0], Imovel: imovel, Inquilino: inq, } fmt.Println(new_contrato) generateContract(new_contrato, Settings.TEMPLATE_FILE, Settings.OUTPUT_FILE) if Settings.SEND_EMAIL == "true" { utils.SendEmail(Settings.EMAIL_ADDRESS, Settings.EMAIL_PASSWORD, new_contrato.Email, "Contrato de Locação", "Contrato de Locação em anexo.", Settings.OUTPUT_FILE) } template, _ := template.ParseFiles("template/new_contrato_status.html") template.Execute(rw, new_contrato) }
func (engine *HTMLTemplateEngine) SoggyEngine(writer io.Writer, filename string, options interface{}) error { template, err := template.ParseFiles(filename) if err != nil { return err } return template.Execute(writer, options) }
func (e Event) GetHTMLView(c appengine.Context) string { buffer := new(bytes.Buffer) var tmpltxt = `<label>Event Title: </label><a href="https://orgreminders.appspot.com/editevent?id={{.Key}}">{{.Title}}</a> <br> <label>When Due: </label>{{.DueFormatted}} <br> <label>Organization(s): </label>{{range .Orgs}}{{.}},{{end}} <br> <label>Email enabled: </label>{{.Email}} <br> <label>Text Enabled: </label>{{.Text}} <br> <label>Email Message: </label><br><div class="msgbody">{{.EmailMessage}}</div> <br> <label>Text Message: </label><br><div class="msgbody"><pre>{{.TextMessage}}</pre></div> <br>` template, terr := template.New("foo").Parse(tmpltxt) if terr != nil { c.Infof("error parsing event html template: %v", terr) return "" } template.Execute(buffer, e) return buffer.String() }
func RenderTemplate(w http.ResponseWriter, r *http.Request, templateName string, templateContext map[string]interface{}) { var paletteItems []*Thing for i := 0; i < 10; i++ { thing := World.ThingForId(ThingId(i)) if thing != nil { paletteItems = append(paletteItems, thing) } } context := map[string]interface{}{ "CsrfToken": nosurf.Token(r), "Config": map[string]interface{}{ "Debug": Config.Debug, "ServiceName": Config.ServiceName, "HostName": Config.HostName, }, "Account": context.Get(r, ContextKeyAccount), // could be nil "PaletteItems": paletteItems, } // If e.g. Account was provided by the caller, it overrides our default one. for k, v := range templateContext { context[k] = v } template := getTemplate(templateName) err := template.Execute(w, context) if err != nil { log.Println("Error executing index.html template:", err.Error()) } }
func main() { mux := http.NewServeMux() stormpathMiddleware := stormpathweb.NewStormpathMiddleware(mux, nil) stormpathMiddleware.SetPreLoginHandler(func(w http.ResponseWriter, r *http.Request, account *stormpath.Account) bool { fmt.Println("--> Pre Login") return true }) stormpathMiddleware.SetPostLoginHandler(func(w http.ResponseWriter, r *http.Request, account *stormpath.Account) bool { fmt.Println("--> Post Login") return true }) stormpathMiddleware.SetPreRegisterHandler(func(w http.ResponseWriter, r *http.Request, account *stormpath.Account) bool { fmt.Println("--> Pre Register") return true }) stormpathMiddleware.SetPostRegisterHandler(func(w http.ResponseWriter, r *http.Request, account *stormpath.Account) bool { fmt.Println("--> Post Register") return true }) mux.Handle("/", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.URL.Path != "/" { http.NotFound(w, r) return } account := stormpathMiddleware.GetAuthenticatedAccount(w, r) w.Header().Add("Content-Type", "text/html") template, err := template.New("hello").Parse(helloTemplate) if err != nil { fmt.Fprint(w, err) return } model := map[string]interface{}{ "account": account, "loginUri": stormpathweb.Config.LoginURI, "logoutUri": stormpathweb.Config.LogoutURI, } if account != nil { model["name"] = account.GivenName } template.Execute(w, model) })) go func() { log.Println(http.ListenAndServe("localhost:6060", nil)) }() fmt.Println("Starting example in port 8080 CTRL+C to stop") log.Fatal(http.ListenAndServe(":8080", stormpathMiddleware)) }
func resultsHandler(w http.ResponseWriter, r *http.Request) { html := "" for _, pic := range pics { html += fmt.Sprintf("<div><img src='%v' /></div>", pic) } result_pics := Pic{template.HTML(html)} template, _ := template.ParseFiles("results.html") template.Execute(w, result_pics) }
func main() { mux := http.NewServeMux() stormpath := stormpathweb.NewStormpathMiddleware(mux, []string{"/"}) stormpath.PreLoginHandler = stormpathweb.UserHandler(func(w http.ResponseWriter, r *http.Request, ctx context.Context) context.Context { fmt.Println("--> Pre Login") return nil }) stormpath.PostLoginHandler = stormpathweb.UserHandler(func(w http.ResponseWriter, r *http.Request, ctx context.Context) context.Context { fmt.Println("--> Post Login") return nil }) stormpath.PreRegisterHandler = stormpathweb.UserHandler(func(w http.ResponseWriter, r *http.Request, ctx context.Context) context.Context { fmt.Println("--> Pre Register") return nil }) stormpath.PostRegisterHandler = stormpathweb.UserHandler(func(w http.ResponseWriter, r *http.Request, ctx context.Context) context.Context { fmt.Println("--> Post Register") return nil }) mux.Handle("/hello", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { account := stormpath.GetAuthenticatedAccount(w, r) w.Header().Add("Content-Type", "text/html") template, err := template.New("hello").Parse(helloTemplate) if err != nil { fmt.Fprint(w, err) return } model := map[string]interface{}{ "account": account, "loginUri": stormpathweb.Config.LoginURI, "logoutUri": stormpathweb.Config.LogoutURI, } if account != nil { model["name"] = account.GivenName } template.Execute(w, model) })) go func() { log.Println(http.ListenAndServe("localhost:6060", nil)) }() log.Fatal(http.ListenAndServe(":8080", stormpath)) }
func Gerador(rw http.ResponseWriter, r *http.Request) { imovel_list := model.Db.SelectAllImovel() inquilino_list := model.Db.SelectAllInquilino() type Gerador struct { Imovel_list []structs.Imovel Inquilino_list []structs.Inquilino } gerador := Gerador{imovel_list, inquilino_list} template, _ := template.ParseFiles("template/gerador.html") template.Execute(rw, gerador) }
func ValidateLoginTemplate(templateContent []byte) []error { var allErrs []error template, err := template.New("loginTemplateTest").Parse(string(templateContent)) if err != nil { return append(allErrs, err) } // Execute the template with dummy values and check if they're there. form := LoginForm{ Action: "MyAction", Error: "MyError", Names: LoginFormFields{ Then: "MyThenName", CSRF: "MyCSRFName", Username: "******", Password: "******", }, Values: LoginFormFields{ Then: "MyThenValue", CSRF: "MyCSRFValue", Username: "******", }, } var buffer bytes.Buffer err = template.Execute(&buffer, form) if err != nil { return append(allErrs, err) } output := buffer.Bytes() var testFields = map[string]string{ "Action": form.Action, "Error": form.Error, "Names.Then": form.Names.Then, "Names.CSRF": form.Values.CSRF, "Names.Username": form.Names.Username, "Names.Password": form.Names.Password, "Values.Then": form.Values.Then, "Values.CSRF": form.Values.CSRF, "Values.Username": form.Values.Username, } for field, value := range testFields { if !bytes.Contains(output, []byte(value)) { allErrs = append(allErrs, errors.New(fmt.Sprintf("template is missing parameter {{ .%s }}", field))) } } return allErrs }
func rootHandler(w http.ResponseWriter, r *http.Request) { context := appengine.NewContext(r) bulletinQuery := datastore.NewQuery("BulletinRecord").Order("-Date").Limit(1) bulletins := make([]BulletinRecord, 0, 1) if _, error := bulletinQuery.GetAll(context, &bulletins); error != nil { http.Error(w, error.Error(), http.StatusInternalServerError) return } template, _ := template.ParseFiles("static/templates/index.html") template.Execute(w, withIdentifiers(bulletins)[0]) }
func main() { // create an output directory (the assets subdirectory here because its // parent will be created as a matter of course) err := os.MkdirAll(TargetAssetsDir, 0755) if err != nil { log.Fatal(err.Error()) } template, err := ace.Load("index", "", &ace.Options{ DynamicReload: true, FuncMap: templateFuncMap(), }) if err != nil { log.Fatal(err.Error()) } db, err := wgt2.LoadDatabase(DBFilename) if err != nil { log.Fatal(err.Error()) } var artists []*wgt2.Artist for _, artist := range db.Artists.Data { artists = append(artists, artist) } // Go doesn't exactly make sorting easy ... sort.Sort(artistSlice(artists)) var playlists []*wgt2.Playlist for _, playlist := range db.Playlists.Data { playlists = append(playlists, playlist) } file, err := os.Create(TargetDir + "index") if err != nil { log.Fatal(err.Error()) } defer file.Close() writer := bufio.NewWriter(file) defer writer.Flush() data := map[string]interface{}{ "artists": artists, "playlists": playlists, } if err := template.Execute(writer, data); err != nil { log.Fatal(err.Error()) } }
func (main *MainController) Get(w http.ResponseWriter, r *http.Request) { t, err := t.ParseFiles("views/T.main.tpl", "views/T.navbar.tpl", "views/T.foot.tpl") if err != nil { log.Println(err) } cookie, _ := r.Cookie("username") user := m.User{} if cookie != nil { user.UserName = cookie.Value } t.Execute(w, &user) }
// ValidateErrorPageTemplate ensures the given template does not error when rendered with an ErrorData object as input func ValidateErrorPageTemplate(templateContent []byte) []error { var allErrs []error template, err := template.New("errorPageTemplateTest").Parse(string(templateContent)) if err != nil { return append(allErrs, err) } var buffer bytes.Buffer err = template.Execute(&buffer, ErrorData{}) if err != nil { return append(allErrs, err) } return allErrs }
func index(w http.ResponseWriter, r *http.Request) error { host, _ := config.GetString("host") userCreate, _ := config.GetBool("auth:user-registration") scheme, _ := config.GetString("auth:scheme") repoManager, _ := config.GetString("repo-manager") data := map[string]interface{}{ "tsuruTarget": host, "userCreate": userCreate, "nativeLogin": scheme == "" || scheme == "native", "keysEnabled": repoManager == "" || repoManager == "gandalf", } template, err := getTemplate() if err != nil { return err } return template.Execute(w, data) }
func initializeDebugServer(baseConfig *BaseConfig) { Log.Debug("starting debug server...") listener, err := net.ListenTCP("tcp", &net.TCPAddr{ IP: net.ParseIP("127.0.0.1"), Port: 0, // Bind to a random port. }) if err != nil { Log.Errorln("error starting debug server:", err) return } // Publish basic table of contents. template, err := template.New("").Parse(` <html><body> {{range .}} <p><a href="{{.Path}}">{{.Text}}</a></p> {{end}} </body></html>`) if err != nil { panic(err) } toc := []struct { Text string Path string }{ {"Profiling", "/debug/pprof"}, {"Download a 30-second CPU profile", "/debug/pprof/profile"}, {"Download a trace file (add ?seconds=x to specify sample length)", "/debug/pprof/trace"}, {"Requests", "/debug/requests"}, {"Event log", "/debug/events"}, } http.HandleFunc("/debug", func(w http.ResponseWriter, req *http.Request) { template.Execute(w, toc) }) go func() { defer listener.Close() if err := http.Serve(listener, nil); err != nil { Log.Errorln("debug server error:", err) return } }() Log.Printf("debug server listening on http://%s/debug", listener.Addr()) }
func (r HTMLMasterInstance) Render(w http.ResponseWriter) error { layout, ok := r.Templates[r.Layout] if !ok { return fmt.Errorf("Layout %v not found", r.Layout) } template, ok := layout[r.Name] if !ok { return fmt.Errorf("Template %v not found", r.Name) } header := w.Header() if val := header["Content-Type"]; len(val) == 0 { header["Content-Type"] = []string{"text/html; charset=utf-8"} } return template.Execute(w, r.Data) }
func main() { m := martini.Classic() template := template.Must(template.ParseFiles("index.tmpl")) schedule(checkData, 10*time.Minute) checkData() m.Get("/", func(res http.ResponseWriter, req *http.Request) { data := PageData{} data.Green = lastData.Status == gtwifi.GREEN data.Yellow = lastData.Status == gtwifi.YELLOW data.Red = lastData.Status == gtwifi.RED data.Reason = lastData.Reason data.LastUpdated = humanize.Time(lastData.TimeRetrieved) template.Execute(res, data) }) m.Run() }
func Go(c *CedStruct.Config) error { // 清空原有的public文件夹 fileNames, err := CedUtils.FilesInDir(c.PublicDir) if err != nil { return err } for i := 0; i < len(fileNames); i++ { CedUtils.Remove(filepath.Join(c.PublicDir, fileNames[i])) } // 解析所有markdown到html fileNames, err = CedUtils.FilesInDir(c.ContentDir) if err != nil { return err } for i := 0; i < len(fileNames); i++ { // 解析 fileName := fileNames[i] file, err := os.Open(filepath.Join(c.ContentDir, fileName)) if err != nil { continue } data, err := ioutil.ReadAll(file) output := blackfriday.MarkdownCommon(data) file.Close() var doc bytes.Buffer template, _ := template.ParseFiles(filepath.Join(c.TemplateDir, "index.tmpl"), filepath.Join(c.TemplateDir, "root.tmpl")) template.Execute(&doc, string(output)) // 保存 fmt.Println(doc.String()) htmlFileName := strings.Split(fileName, ".")[0] file, err = os.Create(filepath.Join(c.PublicDir, htmlFileName+".html")) if err != nil { return err } file.WriteString(html.UnescapeString(doc.String())) file.Close() } return err }
func newHandler(action Action) http.HandlerFunc { return func(rw http.ResponseWriter, req *http.Request) { actionType := reflect.TypeOf(action) args := []reflect.Value{} for i := 0; i < actionType.NumIn(); i++ { args = append(args, bindArgument(actionType.In(i), req)) } // invoke the action ret := reflect.ValueOf(action).Call(args) // handle the return value of the action log.Printf("First return value is of Kind %s", ret[0].Kind()) switch ret[0].Kind() { case reflect.String: rw.Header().Add("Content-Type", "text/plain") fmt.Fprint(rw, ret[0].String()) case reflect.Slice, reflect.Struct: log.Printf("Type of first return value: %s", ret[0].Type().Name()) switch ret[0].Type().Name() { case "View": view := ret[0].Interface().(View) rw.Header().Add("Content-Type", "text/html") template, _ := template.New(view.Name).Parse(Templates[view.Name]) template.Execute(rw, view.Model) default: rw.Header().Add("Content-Type", "application/json") encoder := json.NewEncoder(rw) encoder.Encode(ret[0].Interface()) } } } }
func ValidateSelectProviderTemplate(templateContent []byte) []error { var allErrs []error template, err := template.New("selectProviderTemplateTest").Parse(string(templateContent)) if err != nil { return append(allErrs, err) } // Execute the template with dummy values and check if they're there. providerData := ProviderData{ Providers: []handlers.ProviderInfo{ { Name: "provider_1", URL: "http://example.com/redirect_1/", }, { Name: "provider_2", URL: "http://example.com/redirect_2/", }, }, } var buffer bytes.Buffer err = template.Execute(&buffer, providerData) if err != nil { return append(allErrs, err) } output := buffer.Bytes() // We only care that they are using the URLs we provide, and that they are iterating over all providers // for when multiple providers are allowed if !bytes.Contains(output, []byte(providerData.Providers[1].URL)) { allErrs = append(allErrs, errors.New("template must iterate over all {{.Providers}} and use the {{ .URL }} for each one")) } return allErrs }
func (c *Canvas) renderHtml(w http.ResponseWriter, r *http.Request) error { container := `<!DOCTYPE HTML> <!-- http://www.html5canvastutorials.com/tutorials/html5-canvas-lines/ --> <html> <head> <script src="/jquery.js"></script> <style> body { margin: 0px; padding: 0px; } canvas { border: 1px dashed rgb(170, 170, 170); position:absolute; top:100px; left:100px; visibility: hidden; } </style> </head> <body> <canvas width="{{.Width}}" height="{{.Height}}"></canvas> <canvas width="{{.Width}}" height="{{.Height}}"></canvas> <script> var currentData = [] var canvases = document.getElementsByTagName('canvas'); var contexts = [] contexts[0] = canvases[0].getContext('2d'); contexts[1] = canvases[1].getContext('2d'); var context = contexts[0] var bufferIndex = 0 var intervalId = 0 function getMoreCommands() { if (currentData.length == 0) { $.ajaxSetup({async: false}); try { $.get("/command", {id:"{{.Unique}}"}, function(data) { currentData = data.split("~"); }) .fail(function() { currentData = ["END"] }); } catch(e) { currentData = ["END"] } } } var nextMouseMoveEvent = 0 function postMouseEvent(cmdName, e) { if (e.offsetX == undefined) { x = e.originalEvent.layerX; y = e.originalEvent.layerY; } else { x = e.offsetX; y = e.offsetY; } if (x == undefined || y == undefined) { return; } if (cmdName == "MOUSEMOVE") { var now = new Date().getTime(); if (now < nextMouseMoveEvent) { return; } nextMouseMoveEvent = now + 30; // throttle to 30ms } var cmd = cmdName + " " + x + " " + y $.ajaxSetup({async: true}); $.post("/command", {id:"{{.Unique}}", cmd:cmd}) } function parseBool(b) { return b == "true" } function drawFrame() { getMoreCommands() while (currentData.length > 0) { var commandString = currentData.shift() var command = commandString.split("|"); if (command[0] == "END") { clearInterval(intervalId) } else if (command[0] == "CLEARFRAME") { contexts[bufferIndex].clearRect( 0, 0, canvases[bufferIndex].width, canvases[bufferIndex].height); } else if (command[0] == "SHOWFRAME") { canvases[bufferIndex].style.visibility='visible'; canvases[1-bufferIndex].style.visibility='hidden'; bufferIndex = 1 - bufferIndex context = contexts[bufferIndex] break; } else if (command[0] == "beginPath") { context.beginPath(); } else if (command[0] == "moveTo") { context.moveTo(parseFloat(command[1]), parseFloat(command[2])); } else if (command[0] == "lineTo") { context.lineTo(parseFloat(command[1]), parseFloat(command[2])); } else if (command[0] == "stroke") { context.stroke(); } else if (command[0] == "arc") { context.arc(parseFloat(command[1]), parseFloat(command[2]), parseFloat(command[3]), parseFloat(command[4]), parseFloat(command[5]), parseBool(command[6])); } else if (command[0] == "fillStyle") { context.fillStyle = command[1] } else if (command[0] == "fill") { context.fill() } else if (command[0] == "lineWidth") { context.lineWidth = parseFloat(command[1]) } else if (command[0] == "strokeStyle") { context.strokeStyle = command[1] } else if (command[0] == "fillRect") { context.fillRect(parseFloat(command[1]), parseFloat(command[2]), parseFloat(command[3]), parseFloat(command[4])) } else if (command[0] == "strokeRect") { context.strokeRect(parseFloat(command[1]), parseFloat(command[2]), parseFloat(command[3]), parseFloat(command[4])) } else if (command[0] == "clearRect") { context.clearRect(parseFloat(command[1]), parseFloat(command[2]), parseFloat(command[3]), parseFloat(command[4])) } } } $(canvases[0]).click(function(e) { postMouseEvent("MOUSECLICK", e); }); $(canvases[0]).mousemove(function(e) { postMouseEvent("MOUSEMOVE", e); }); $(canvases[1]).click(function(e) { postMouseEvent("MOUSECLICK", e); }); $(canvases[1]).mousemove(function(e) { postMouseEvent("MOUSEMOVE", e); }); intervalId = setInterval("drawFrame()", 30) </script> </body> </html>` template, err := template.New("basic").Parse(container) if err != nil { return err } err = template.Execute(w, c) return err }
func handler(w http.ResponseWriter, r *http.Request) { template, _ := template.ParseFiles("templates/listing.html") themedata := openXML("db/themedata.xml") template.Execute(w, &themedata) }
func Imoveis(rw http.ResponseWriter, r *http.Request) { imovel_list := model.Db.SelectAllImovel() template, _ := template.ParseFiles("template/imoveis.html") template.Execute(rw, imovel_list) }
func Inquilinos(rw http.ResponseWriter, r *http.Request) { inquilino_list := model.Db.SelectAllInquilino() template, _ := template.ParseFiles("template/inquilinos.html") fmt.Println(inquilino_list) template.Execute(rw, inquilino_list) }