本文整理汇总了Golang中template.New函数的典型用法代码示例。如果您正苦于以下问题:Golang New函数的具体用法?Golang New怎么用?Golang New使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了New函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: 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
HTML_DIRECTORY_LISTING_SUCCESS_TEMPLATE, _ = template.New("directory_listing_success").Parse(HTML_DIRECTORY_LISTING_SUCCESS_TEMPLATE_STRING)
HTML_DIRECTORY_LISTING_ERROR_TEMPLATE, _ = template.New("directory_listing_error").Parse(HTML_DIRECTORY_LISTING_ERROR_TEMPLATE_STRING)
}
示例2: init
func init() {
rand.Seed(time.Nanoseconds())
// TODO: This should end up in a configuration file
schema = &grapher.Schema{FileSchemas: map[string]*grapher.FileSchema{
"application/x-lightwave-book": &grapher.FileSchema{EntitySchemas: map[string]*grapher.EntitySchema{
"application/x-lightwave-entity-chapter": &grapher.EntitySchema{FieldSchemas: map[string]*grapher.FieldSchema{
"after": &grapher.FieldSchema{Type: grapher.TypeEntityBlobRef, ElementType: grapher.TypeNone, Transformation: grapher.TransformationNone},
"title": &grapher.FieldSchema{Type: grapher.TypeString, ElementType: grapher.TypeNone, Transformation: grapher.TransformationLatest},
"color": &grapher.FieldSchema{Type: grapher.TypeInt64, ElementType: grapher.TypeNone, Transformation: grapher.TransformationLatest}}},
"application/x-lightwave-entity-page": &grapher.EntitySchema{FieldSchemas: map[string]*grapher.FieldSchema{
"after": &grapher.FieldSchema{Type: grapher.TypeEntityBlobRef, ElementType: grapher.TypeNone, Transformation: grapher.TransformationNone},
"title": &grapher.FieldSchema{Type: grapher.TypeString, ElementType: grapher.TypeNone, Transformation: grapher.TransformationLatest},
"chapter": &grapher.FieldSchema{Type: grapher.TypeEntityBlobRef, ElementType: grapher.TypeNone, Transformation: grapher.TransformationNone},
"page": &grapher.FieldSchema{Type: grapher.TypePermaBlobRef, ElementType: grapher.TypeNone, Transformation: grapher.TransformationNone}}}}},
"application/x-lightwave-page": &grapher.FileSchema{EntitySchemas: map[string]*grapher.EntitySchema{
"application/x-lightwave-entity-content": &grapher.EntitySchema{FieldSchemas: map[string]*grapher.FieldSchema{
"layout": &grapher.FieldSchema{Type: grapher.TypeString, ElementType: grapher.TypeNone, Transformation: grapher.TransformationNone},
"style": &grapher.FieldSchema{Type: grapher.TypeMap, ElementType: grapher.TypeNone, Transformation: grapher.TransformationMerge},
"cssclass": &grapher.FieldSchema{Type: grapher.TypeString, ElementType: grapher.TypeNone, Transformation: grapher.TransformationLatest},
"text": &grapher.FieldSchema{Type: grapher.TypeString, ElementType: grapher.TypeNone, Transformation: grapher.TransformationMerge}}}}}}}
frontPageTmpl = template.New(nil)
frontPageTmpl.SetDelims("{{", "}}")
if err := frontPageTmpl.ParseFile("notebook.html"); err != nil {
frontPageTmplErr = fmt.Errorf("tmpl.ParseFile failed: %v", err)
return
}
appLoginPageTmpl = template.New(nil)
appLoginPageTmpl.SetDelims("{{", "}}")
if err := appLoginPageTmpl.ParseFile("applogin.html"); err != nil {
appLoginPageTmplErr = fmt.Errorf("tmpl.ParseFile failed: %v", err)
return
}
http.HandleFunc("/", handleFrontPage)
http.HandleFunc("/private/submit", handleSubmit)
http.HandleFunc("/private/open", handleOpen)
http.HandleFunc("/private/close", handleClose)
http.HandleFunc("/private/listpermas", handleListPermas)
http.HandleFunc("/private/listinbox", handleListInbox)
http.HandleFunc("/private/listunread", handleListUnread)
http.HandleFunc("/private/invitebymail", handleInviteByMail)
http.HandleFunc("/private/inboxitem", handleInboxItem)
http.HandleFunc("/private/markasread", handleMarkAsRead)
http.HandleFunc("/private/markasarchived", handleMarkAsArchived)
http.HandleFunc("/signup", handleSignup)
http.HandleFunc("/logout", handleLogout)
http.HandleFunc("/login", handleLogin)
http.HandleFunc("/applogin", handleAppLogin)
http.HandleFunc("/internal/notify", handleDelayedNotify)
http.HandleFunc("/_ah/channel/connected/", handleConnect)
http.HandleFunc("/_ah/channel/disconnected/", handleDisconnect)
// http.HandleFunc("/import", handleImport)
}
示例3: init
func init() {
BrowseT = template.New(nil)
BrowseT.SetDelims("{{", "}}")
BrowseT.ParseFile(BrowseTemplatePath)
BrowseChooseT = template.New(nil)
BrowseChooseT.SetDelims("{{", "}}")
BrowseChooseT.ParseFile(BrowseChooseTemplatePath)
}
示例4: main
func main() {
t := make(map[string][]Template)
v := visitor{t}
filepath.Walk(HtmlDir, &v, nil)
indexBinder := IndexBinder{make([]Package, 0), make([]Template, 0)}
for packagePath, templates := range v.Templates {
filename := packagePath[strings.LastIndex(packagePath, "/")+1:]
binder := Binder{filename, templates}
temp := template.New("")
p, err := temp.Parse(getTemplate())
if err != nil {
fmt.Println("Error!", err.String())
return
}
htmlDirWithoutSlash := HtmlDir
if strings.HasSuffix(htmlDirWithoutSlash, "/") {
htmlDirWithoutSlash = htmlDirWithoutSlash[0 : len(htmlDirWithoutSlash)-1]
}
htmlDirWithoutBaseDir := htmlDirWithoutSlash[0:strings.LastIndex(htmlDirWithoutSlash, "/")]
fullFilename := fmt.Sprint(htmlDirWithoutBaseDir, "/", packagePath, "/", filename, ".go")
fmt.Println("fullFilename: ", fullFilename)
f, _ := os.Create(fullFilename)
defer f.Close()
p.Execute(f, binder)
indexBinder.Packages = append(indexBinder.Packages, Package{PackageName: filename, PackagePath: packagePath, PackagePathUnderscores: strings.Replace(packagePath, "/", "_", -1)})
for _, template := range templates {
indexBinder.Templates = append(indexBinder.Templates, template)
}
}
tempIndex := template.New("")
tempIndexParsed, err := tempIndex.Parse(getTemplateIndex())
if err != nil {
fmt.Println("Error!", err.String())
return
}
fIndex, _ := os.Create(IndexFile)
defer fIndex.Close()
tempIndexParsed.Execute(fIndex, indexBinder)
fmt.Println("Done!!")
}
示例5: generateRouter
func generateRouter() {
//mkdir for the initiator
err := os.MkdirAll(*TargetFullPath+"/router/", 0755)
if err != nil {
fmt.Println("Unable to create directory, ", err.String())
}
f, err := os.Create(*TargetFullPath + "/router/" + "router.go")
if err != nil {
fmt.Println(err.String())
}
defer f.Close()
var templ *template.Template
templ = template.New(nil)
templ.SetDelims("<%", "%>")
err = templ.Parse(routerTemplate)
if err != nil {
fmt.Println(err.String())
}
err = templ.Execute(f, map[string]interface{}{
"PackageName": *PackageName,
"ServiceName": *ServiceName,
})
if err != nil {
fmt.Println(err.String())
}
}
示例6: init
func init() {
chatTempl = template.New(nil)
chatTempl.SetDelims("«", "»")
if err := chatTempl.Parse(chatStr); err != nil {
panic("template error: " + err.String())
}
}
示例7: parse
func parse(name, s string) *template.Template {
t, err := template.New(name).Parse(s)
if err != nil {
panic(fmt.Sprintf("%q: %s", name, err))
}
return t
}
示例8: ShowErrors
func ShowErrors(templateString string) Middleware {
if templateString == "" {
templateString = `
<html>
<body>
<p>
{{.Error|html}}
</p>
</body>
</html>
`
}
errorTemplate := template.Must(template.New("error").Parse(templateString))
return func(env Env, app App) (status Status, headers Headers, body Body) {
defer func() {
if err := recover(); err != nil {
buffer := bytes.NewBufferString("")
errorTemplate.Execute(buffer, struct{ Error string }{fmt.Sprintf("%s", err)})
status = 500
headers = Headers{}
body = Body(buffer.String())
}
}()
return app(env)
}
}
示例9: init
func init() {
homeTempl = template.New("")
//homeTempl.SetDelims("<<", ">>")
if _, err := homeTempl.Parse(homeStr); err != nil {
panic("template error: " + err.String())
}
}
示例10: init
func init() {
homeTempl = template.New(nil)
homeTempl.SetDelims("<<", ">>")
if err := homeTempl.ParseFile("index.html"); err != nil {
panic("template error: " + err.String())
}
}
示例11: articleJSON
// articleJSON handles generates the JSON of a specified Article struct. This is
// used as part of the admin manager, to be able to preview and edit the articles
// with JSON.
func articleJSON(w http.ResponseWriter, r *http.Request) {
// Sanity check to ensure that at least /some/ sort of ID was given
path := strings.Split(r.URL.Path, "/")
if len(path) < 4 || path[3] == "" {
errorGenerator(w, "No Article ID provided", 404)
return
}
// Fetch Article struct based on ID given
c := appengine.NewContext(r)
a, err := getArticle(c, path[3])
check(err)
// Generate JSON via the template. Can't use the JSON marshaller because we
// don't want to represent the ShortBody & Body as JSON-encoded []bytes, but
// as JSON-escaped strings. The template function is also provided with a
// special function to escape the ShortBody & Body for JSON representation.
t := template.New("articleJSON")
t.Funcs(template.FuncMap{"json": escapeForJSON})
t, err = t.ParseFile("templates/article.json")
check(err)
// Execute the template, using the Article struct as a source
err = t.Execute(w, a)
check(err)
}
示例12: articlesIndex
// articlesIndex is the handler for the site's index page.
// It shows up to the last 10 article summaries (all public info except
// for the Body) on a single page.
func articlesIndex(w http.ResponseWriter, r *http.Request) {
// Get the user-entered offset, or default to a zero offset.
offsetS := r.FormValue("Page")
var offset int
if len(offsetS) > 0 {
offset64, err := strconv.Btoi64(offsetS, 10)
check(err)
offset = int(offset64)
} else {
offset = 0
}
// Fetch public data from datastore, up to 10, with offset `offset * 10`
c := appengine.NewContext(r)
q := datastore.NewQuery("Article").Order("-Date").Filter("Public =", true).Limit(10).Offset(10 * offset)
a := make([]Article, 0, 10)
_, err := q.GetAll(c, &a)
check(err)
// Prepares the `indexTemplate.html` template
t := template.New("index")
t, err = t.ParseFile("templates/indexTemplate.html")
check(err)
// Executes the template, providing the data gathered from the datastore
err = t.Execute(w, a)
check(err)
}
示例13: init
func init() {
homeTempl = template.New(nil)
homeTempl.SetDelims("«", "»")
if err := homeTempl.Parse(homeStr2); err != nil {
panic("template error: " + err.String())
}
}
示例14: add
// Add adds a given template string to the template manager.
// If any errors occur, err will be non-nil.
func (m *Manager) add(s string, id string, mustParse bool) (t *Template,
err os.Error) {
tt := template.New(m.fmap)
tt.SetDelims(m.ldelim, m.rdelim)
// Parse the template.
if mustParse {
err := tt.Parse(s)
if err != nil {
panic(err)
}
} else {
err := tt.Parse(s)
if err != nil {
return
}
}
t = &Template{
m: m,
cache: tt}
// Add template to the manager.
m.tStrings[id] = t
return
}
示例15: TestAutoesc
func TestAutoesc(t *testing.T) {
for _, testCase := range testCases {
name := testCase.name
tmpl := template.New(name)
tmpl, err := tmpl.Parse(testCase.input)
if err != nil {
t.Errorf("%s: failed to parse template: %s", name, err)
continue
}
Escape(tmpl)
buffer := new(bytes.Buffer)
err = tmpl.Execute(buffer, testData)
if err != nil {
t.Errorf("%s: template execution failed: %s", name, err)
continue
}
output := testCase.output
actual := buffer.String()
if output != actual {
t.Errorf("%s: escaped output: %q != %q",
name, output, actual)
}
}
}