本文整理汇总了Golang中html/template.New函数的典型用法代码示例。如果您正苦于以下问题:Golang New函数的具体用法?Golang New怎么用?Golang New使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了New函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: main
func main() {
// apiAuth guards access to api group
apiAuth := mw.HTTPAuth("API", func(user, pass string) bool {
return pass == "Secret"
})
// dashboardAuth guards access to dashboard group
dashboardAuth := mw.HTTPAuth("Dashboard", func(user, pass string) bool {
return pass == "Password"
})
// set up root router with Logger, Recovery and LocalStorage middleware
w := wok.Default()
// Index page
idxTpl := template.Must(template.New("index").Parse("<h1>Hello</h1>"))
w.GET("/", render.Template(idxTpl))(index)
// api is a group of routes with common authentication and result rendering
api := w.Group("/api", apiAuth, render.JSON)
{
api.GET("/")(apiIndex)
api.GET("/:id")(apiDetail)
}
// dash is an example of another separate route group
dash := w.Group("/dash", dashboardAuth)
{
tpl, _ := template.New("dash").Parse("<h1>Hello {{ .User }}</h1>")
dash.GET("/", render.Template(tpl))(dashIndex)
}
http.ListenAndServe(":8080", w)
}
示例2: main
func main() {
data := map[string]interface{}{
"Title": "Hello World!",
}
t := template.New("HELLO")
err := t.ExecuteTemplate(os.Stdout, "Template-Html.tmpl", data)
// not working, empty output.
// So the template file MUST be specified twice!
var templates = template.Must(t.ParseFiles("Template-Html.tmpl"))
err = templates.ExecuteTemplate(os.Stdout, "Template-Html.tmpl", data)
// working
fmt.Println("\n\n")
// This option, need to use the template file twice, once for
// `ParseFiles`, then for `ExecuteTemplate`. That looks awkward and
// unnecessary. The following one looks straightforward to me.
t = template.New("Test template")
t, err = t.Parse("<title>{{ .Title }}</title>")
// working
t, err = template.ParseFiles("Template-Html.tmpl")
// working now! Note the difference!!
checkError(err)
err = t.Execute(os.Stdout, data)
fmt.Println("\n\nTemplate name is : ", t.Name())
}
示例3: transactionStatus
//transactionStatus handles the transactionStatusRequest as defined in the WSDL
//response is the XML version of the client callback
func (c2b *C2B) transactionStatus(data interface{}) http.HandlerFunc {
return func(rw http.ResponseWriter, r *http.Request) {
parsed := data.(*TransactionStatusRequest)
validate(rw,
validAuthDetails("", parsed.Header.CheckoutHeader),
validPassedConfirmTrxID(parsed.Body.TransactionStatus.TransID, parsed.Body.TransactionStatus.MerchantTransID),
)
trx := c2b.idExists(parsed.Body.TransactionStatus.MerchantTransID, parsed.Body.TransactionStatus.TransID)
if trx == nil {
resp := new(ProcessCheckoutResponse)
resp.ReturnCode = transactionMismatch
resp.Description = "transaction details are different from original captured request details."
resp.TransactionID = ""
resp.ConfirmTrx = true
tpl, _ := template.New("response").Parse(processCheckOutRespTPL)
tpl.Execute(rw, resp)
return
}
tpl, _ := template.New("response").Parse(callBackRespTPL)
tpl.Execute(rw, trx)
}
}
示例4: sendMail
// Sends email based on the result of all batches
func (r *GlobalResults) sendMail() {
funcMap := template.FuncMap{
"odd": func(i int) bool { return i%2 == 0 },
}
tHeader := template.Must(template.New("header").Parse(emailTemplateHtmlHeader))
tBody := template.Must(template.New("body").Funcs(funcMap).Parse(emailTemplateHtmlBody))
var docHeader bytes.Buffer
tHeader.Execute(&docHeader, r.Author)
for _, br := range r.BatchResultList {
var docBody bytes.Buffer
tBody.Execute(&docBody, br)
TraceActivity.Printf("----------------------------------------------------------------------------- \n")
TraceActivity.Printf("GeneratedCOntent : \n")
TraceActivity.Printf("%s\n", docBody.String())
TraceActivity.Printf("----------------------------------------------------------------------------- \n")
var buffer bytes.Buffer
buffer.WriteString(docHeader.String())
buffer.WriteString(docBody.String())
br.Smtp.sendEmailHtml(br, buffer.String())
}
}
示例5:
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)
}
示例6: mainMenu
func mainMenu(w http.ResponseWriter, r *http.Request) {
t, err := template.New("foo").Parse(`<html><body><h1>Bootleg</h1>{{.}}</body></html>`)
if err != nil {
panic(err)
}
buf := bytes.Buffer{}
type ServerArg struct {
Name string
Body template.HTML
}
for _, srv := range srvs {
t1, err1 := template.New("bar").Parse(`<h2>{{.Name}}</h2><ul>{{.Body}}</ul>`)
if err1 != nil {
panic(err1)
}
buf1 := bytes.Buffer{}
formatDir(srv.files, &buf1)
t1.Execute(&buf, ServerArg{srv.name, template.HTML(buf1.String())})
}
t.Execute(w, template.HTML(buf.String()))
}
示例7: LoadTemplates
func LoadTemplates() {
EmailTmpl = text_template.Must(text_template.New("Email").ParseGlob(
filepath.Join(cfg.TemplatesDir, "email", "*.txt"),
))
SignupTmpl = template.Must(template.New("Signup").ParseFiles(
filepath.Join(cfg.TemplatesDir, "account", "base.html"),
filepath.Join(cfg.TemplatesDir, "account", "signup.html"),
))
SignupOkTmpl = template.Must(template.New("SignupOk").ParseFiles(
filepath.Join(cfg.TemplatesDir, "account", "base.html"),
filepath.Join(cfg.TemplatesDir, "account", "signup_ok.html"),
))
HelloTmpl = template.Must(template.New("Hello").ParseFiles(
filepath.Join(cfg.TemplatesDir, "account", "base.html"),
filepath.Join(cfg.TemplatesDir, "account", "hello.html"),
))
LoginTmpl = template.Must(template.New("Login").ParseFiles(
filepath.Join(cfg.TemplatesDir, "account", "base.html"),
filepath.Join(cfg.TemplatesDir, "account", "login.html"),
))
}
示例8: TestTemplate_FuncMap_url
func TestTemplate_FuncMap_url(t *testing.T) {
app := kocha.NewTestApp()
funcMap := template.FuncMap(app.Template.FuncMap)
func() {
tmpl := template.Must(template.New("test").Funcs(funcMap).Parse(`{{url "root"}}`))
var buf bytes.Buffer
if err := tmpl.Execute(&buf, nil); err != nil {
panic(err)
}
actual := buf.String()
expected := "/"
if !reflect.DeepEqual(actual, expected) {
t.Errorf("Expect %q, but %q", expected, actual)
}
}()
func() {
tmpl := template.Must(template.New("test").Funcs(funcMap).Parse(`{{url "user" 713}}`))
var buf bytes.Buffer
if err := tmpl.Execute(&buf, nil); err != nil {
panic(err)
}
actual := buf.String()
expected := "/user/713"
if !reflect.DeepEqual(actual, expected) {
t.Errorf("Expect %v, but %v", expected, actual)
}
}()
}
示例9: templateFinder
// templateFinder returns a directory string where template "index.html" is located.
// We also parse the template to test whether or not we should boot any further.
func templateFinder() string {
templateDir := "./templates/"
// Try to parse
_, err = template.New("Index").Funcs(funcMap).ParseFiles(templateDir + "index.html")
if err == nil {
return templateDir
}
// Does not exist
if strings.Contains(err.Error(), "no such file") {
log.Println("Creating ./templates")
err = RestoreAssets(".", "templates")
if err != nil {
log.Fatalln(err)
}
// Try to parse
_, err = template.New("Index").Funcs(funcMap).ParseFiles(templateDir + "index.html")
if err == nil {
return templateDir
}
} else if strings.Contains(err.Error(), "not defined") {
log.Println("Template is bad.", err.Error())
os.Exit(1)
}
// The error is probably permissions and theres nothing more to be done
log.Fatalln("Template:", err)
return ""
}
示例10: ServeHTTP
func (mh ManifestHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
q := req.URL.Query()
name, ok := q["p"]
if !ok || len(name) != 1 {
w.Header().Set("Content-Type", "text/html")
t, err := template.New("show").Parse(ManifestIndexTemplate)
options.FailIf(err, "can't parse template")
err = t.Execute(w, mh)
options.FailIf(err, "can't execute template")
return
}
fmt.Printf("request for: %s\n", name[0])
var p auth.Prin
if _, err := fmt.Sscanf("("+name[0]+")", "%v", &p); err != nil {
http.NotFound(w, req)
return
}
m := tao.DeriveManifest(&p)
var b bytes.Buffer
Dump(indent.NewHtmlWriter(&b, "h2"), tao.Manifest{"Principal Manifest": m})
s := b.String()
w.Header().Set("Content-Type", "text/html")
t, err := template.New("show").Parse(ManifestTemplate)
options.FailIf(err, "can't parse template")
err = t.Execute(w, template.HTML(s))
options.FailIf(err, "can't execute template")
}
示例11: TestTemplateFuncs_date
func TestTemplateFuncs_date(t *testing.T) {
base := `{{date . "%v"}}`
now := time.Now()
tmpl := template.Must(template.New("test").Funcs(TemplateFuncs).Parse(fmt.Sprintf(base, "2006/01/02 15:04:05.999999999")))
var buf bytes.Buffer
if err := tmpl.Execute(&buf, now); err != nil {
panic(err)
}
actual := buf.String()
expected := now.Format("2006/01/02 15:04:05.999999999")
if !reflect.DeepEqual(actual, expected) {
t.Errorf("Expect %q, but %q", expected, actual)
}
tmpl = template.Must(template.New("test").Funcs(TemplateFuncs).Parse(fmt.Sprintf(base, "Jan 02 2006 03:04.999999999")))
buf.Reset()
if err := tmpl.Execute(&buf, now); err != nil {
panic(err)
}
actual = buf.String()
expected = now.Format("Jan 02 2006 03:04.999999999")
if !reflect.DeepEqual(actual, expected) {
t.Errorf("Expect %q, but %q", expected, actual)
}
}
示例12: init
func init() {
ALL_METHODS = []string{GET, HEAD, POST, CONNECT, DELETE, OPTIONS, PUT, TRACE}
defaultMimeTypes = make(map[string]string)
defaultMimeTypes[".htm"] = MIME_TYPE_HTML
defaultMimeTypes[".html"] = MIME_TYPE_HTML
defaultMimeTypes[".xhtml"] = MIME_TYPE_XHTML_XML
defaultMimeTypes[".xml"] = MIME_TYPE_XML
defaultMimeTypes[".css"] = MIME_TYPE_CSS
defaultMimeTypes[".js"] = MIME_TYPE_JAVASCRIPT
defaultMimeTypes[".json"] = MIME_TYPE_JSON
defaultMimeTypes[".jpg"] = MIME_TYPE_JPEG
defaultMimeTypes[".jpeg"] = MIME_TYPE_JPEG
defaultMimeTypes[".gif"] = MIME_TYPE_GIF
defaultMimeTypes[".png"] = MIME_TYPE_PNG
defaultMimeTypes[".ico"] = MIME_TYPE_ICO
defaultMimeTypes[".swf"] = MIME_TYPE_SWF
defaultMimeTypes[".zip"] = MIME_TYPE_ZIP
defaultMimeTypes[".bz2"] = MIME_TYPE_BZIP2
defaultMimeTypes[".gz"] = MIME_TYPE_GZ
defaultMimeTypes[".tar"] = MIME_TYPE_TAR
defaultMimeTypes[".tgz"] = MIME_TYPE_GZ
defaultMimeTypes[".htc"] = MIME_TYPE_COMPONENT
defaultMimeTypes[".manifest"] = MIME_TYPE_CACHE_MANIFEST
defaultMimeTypes[".svg"] = MIME_TYPE_SVG
defaultMimeTypes[".txt"] = MIME_TYPE_TEXT_PLAIN
defaultMimeTypes[".text"] = MIME_TYPE_TEXT_PLAIN
defaultMimeTypes[".csv"] = MIME_TYPE_CSV
var err error
HTML_DIRECTORY_LISTING_SUCCESS_TEMPLATE, err = template.New("directory_listing_success").Parse(HTML_DIRECTORY_LISTING_SUCCESS_TEMPLATE_STRING)
template.Must(HTML_DIRECTORY_LISTING_SUCCESS_TEMPLATE, err)
HTML_DIRECTORY_LISTING_ERROR_TEMPLATE, err = template.New("directory_listing_error").Parse(HTML_DIRECTORY_LISTING_ERROR_TEMPLATE_STRING)
template.Must(HTML_DIRECTORY_LISTING_ERROR_TEMPLATE, err)
}
示例13: TestTemplateFuncs_url
func TestTemplateFuncs_url(t *testing.T) {
oldAppConfig := appConfig
appConfig = newTestAppConfig()
defer func() {
appConfig = oldAppConfig
}()
tmpl := template.Must(template.New("test").Funcs(TemplateFuncs).Parse(`{{url "root"}}`))
var buf bytes.Buffer
if err := tmpl.Execute(&buf, nil); err != nil {
panic(err)
}
actual := buf.String()
expected := "/"
if !reflect.DeepEqual(actual, expected) {
t.Errorf("Expect %q, but %q", expected, actual)
}
tmpl = template.Must(template.New("test").Funcs(TemplateFuncs).Parse(`{{url "user" 713}}`))
buf.Reset()
if err := tmpl.Execute(&buf, nil); err != nil {
panic(err)
}
actual = buf.String()
expected = "/user/713"
if !reflect.DeepEqual(actual, expected) {
t.Errorf("Expect %v, but %v", expected, actual)
}
}
示例14: Detail
//列出某问题的详细信息,URL,/probliem?detail/pid?<pid>
func (this *ProblemController) Detail(w http.ResponseWriter, r *http.Request) {
class.Logger.Debug("Problem Detail")
this.Init(w, r)
args := this.ParseURL(r.URL.String())
pid, err := strconv.Atoi(args["pid"])
if err != nil {
http.Error(w, "args error", 400)
return
}
problemModel := model.ProblemModel{}
one, err := problemModel.Detail(pid)
if err != nil {
t := template.New("layout.tpl")
t, err = t.ParseFiles("view/layout.tpl", "view/400.tpl")
if err != nil {
class.Logger.Debug(err)
http.Error(w, "tpl error", 500)
return
}
this.Data["Info"] = "No such problem"
this.Data["Title"] = "No such problem"
err = t.Execute(w, this.Data)
if err != nil {
http.Error(w, "tpl error", 500)
return
}
return
}
this.Data["Detail"] = one
if this.Privilege <= config.PrivilegePU && one.Status == config.StatusReverse { // 如果问题状态为普通用户不可见
t := template.New("layout.tpl")
t, err = t.ParseFiles("view/layout.tpl", "view/400.tpl")
if err != nil {
class.Logger.Debug(err)
http.Error(w, "tpl error", 500)
return
}
this.Data["Info"] = "No such problem"
this.Data["Title"] = "No such problem"
err = t.Execute(w, this.Data)
if err != nil {
http.Error(w, "tpl error", 500)
return
}
return
}
this.Data["Privilege"] = this.Privilege
this.Data["Title"] = "Problem — " + strconv.Itoa(pid)
err = this.Execute(w, "view/layout.tpl", "view/problem_detail.tpl")
if err != nil {
http.Error(w, "tpl error", 500)
return
}
}
示例15: RunTemplate
func RunTemplate(reportFilename, templateFile, templateText string, out *os.File, data interface{}, format string) (err error) {
var tmpl *template.Template
var htmpl *htemplate.Template
if templateFile != "" {
if format == "html" {
htmpl, err = htemplate.New(templateFile).ParseGlob(templateFile)
} else {
tmpl, err = template.New(templateFile).ParseGlob(templateFile)
}
} else {
if format == "html" {
htmpl, err = htemplate.New(reportFilename).Parse(templateText)
} else {
tmpl, err = template.New(reportFilename).Parse(templateText)
}
}
if err != nil {
return err
}
if format == "html" {
err = htmpl.Execute(out, data)
} else {
err = tmpl.Execute(out, data)
}
if err != nil {
return err
}
return err
}