当前位置: 首页>>代码示例>>Golang>>正文


Golang template.Execute函数代码示例

本文整理汇总了Golang中html/template.Execute函数的典型用法代码示例。如果您正苦于以下问题:Golang Execute函数的具体用法?Golang Execute怎么用?Golang Execute使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了Execute函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。

示例1:

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)

}
开发者ID:a2800276,项目名称:gaml,代码行数:30,代码来源:template.go

示例2: GetTestServer

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
}
开发者ID:jarias,项目名称:stormpath-sdk-go,代码行数:35,代码来源:web_test.go

示例3: SendEmail

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
}
开发者ID:narma,项目名称:golib,代码行数:30,代码来源:smtp.go

示例4: NewContratoStatus

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)
}
开发者ID:marcelolima,项目名称:leasing_contract_generator,代码行数:29,代码来源:routes.go

示例5: SoggyEngine

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)
}
开发者ID:dbrain,项目名称:soggy,代码行数:7,代码来源:htmltemplateengine.go

示例6: GetHTMLView

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()
}
开发者ID:jlmeeker,项目名称:orgreminders,代码行数:27,代码来源:event.go

示例7: RenderTemplate

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())
	}
}
开发者ID:natmeox,项目名称:mess,代码行数:30,代码来源:web.go

示例8: main

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))
}
开发者ID:jarias,项目名称:stormpath-sdk-go,代码行数:59,代码来源:example.go

示例9: resultsHandler

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)
}
开发者ID:tracymu,项目名称:gutsing,代码行数:11,代码来源:guts.go

示例10: main

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))
}
开发者ID:jxstanford,项目名称:stormpath-sdk-go,代码行数:54,代码来源:example.go

示例11: Gerador

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)
}
开发者ID:marcelolima,项目名称:leasing_contract_generator,代码行数:11,代码来源:routes.go

示例12: ValidateLoginTemplate

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: "MyUsernameName",
			Password: "MyPasswordName",
		},
		Values: LoginFormFields{
			Then:     "MyThenValue",
			CSRF:     "MyCSRFValue",
			Username: "MyUsernameValue",
		},
	}

	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
}
开发者ID:LalatenduMohanty,项目名称:origin,代码行数:52,代码来源:login.go

示例13: rootHandler

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])
}
开发者ID:mufniarz,项目名称:OLMC,代码行数:13,代码来源:web.go

示例14: main

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())
	}
}
开发者ID:brandur,项目名称:wgt2,代码行数:51,代码来源:main.go

示例15: Get

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)

}
开发者ID:jjjachyty,项目名称:ibookings,代码行数:14,代码来源:main.go


注:本文中的html/template.Execute函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。