本文整理汇总了Golang中text/template.ParseGlob函数的典型用法代码示例。如果您正苦于以下问题:Golang ParseGlob函数的具体用法?Golang ParseGlob怎么用?Golang ParseGlob使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了ParseGlob函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: main
func main() {
c, err := config.ReadDefault("wiki.ini")
panicIni(err)
wikiName, err = c.String("wiki", "name")
panicIni(err)
servAddr, err := c.String("wiki", "serv_addr")
panicIni(err)
inDevMode, err = c.Bool("wiki", "dev_mode")
panicIni(err)
log.Printf("Read wiki.ini")
views = template.Must(template.ParseGlob("views/[a-z]*.html"))
log.Printf("Parsed page templates\n")
http.HandleFunc("/", rootHandler)
http.HandleFunc("/delete/", deleteHandler)
http.HandleFunc("/restore/", restoreHandler)
http.HandleFunc("/edit/", editHandler)
http.HandleFunc("/preview", previewHandler)
http.HandleFunc("/save/", saveHandler)
http.HandleFunc("/pages", pagesHandler)
http.HandleFunc("/deleted", deletedHandler)
http.HandleFunc("/versions/", versionsHandler)
http.HandleFunc("/search", searchHandler)
http.Handle("/pub/", http.StripPrefix("/pub/", http.FileServer(http.Dir("pub"))))
http.HandleFunc("/favicon.ico", faviconHandler)
log.Printf("Serving wiki pages from %s...\n", servAddr)
log.Fatal(http.ListenAndServe(servAddr, nil))
}
示例2: main
func main() {
tpl, err := template.ParseGlob("templates/*.gmao")
if err != nil {
log.Fatalln(err)
}
err = tpl.Execute(os.Stdout, nil)
if err != nil {
log.Fatalln(err)
}
err = tpl.ExecuteTemplate(os.Stdout, "vespa.gmao", nil)
if err != nil {
log.Fatalln(err)
}
err = tpl.ExecuteTemplate(os.Stdout, "two.gmao", nil)
if err != nil {
log.Fatalln(err)
}
err = tpl.ExecuteTemplate(os.Stdout, "one.gmao", nil)
if err != nil {
log.Fatalln(err)
}
}
示例3: New
func New(addr string, auth smtp.Auth, templateDir string) (Mailer, error) {
templates, err := template.ParseGlob(filepath.Join(templateDir, "*.tmpl"))
if err != nil {
return nil, err
}
return &defaultMailer{addr, auth, templates}, nil
}
示例4: NewTheme
func NewTheme(tpath string) *Theme {
var err error
var pattern string
var pages []string
var base *template.Template
var tmap = map[string]*template.Template{}
pattern = path.Join(tpath, "*.html")
base = template.Must(template.ParseGlob(pattern))
pattern = path.Join(tpath, "pages", "*.html")
if pages, err = filepath.Glob(pattern); err != nil {
panic(err)
}
for _, tpath := range pages {
var ts *template.Template
if ts, err = base.Clone(); err != nil {
panic(err)
}
if _, err = ts.ParseFiles(tpath); err != nil {
panic(err)
}
tmap[path.Base(tpath)] = ts
}
return &Theme{
Path: tpath,
Templates: tmap,
}
}
示例5: init
func init() {
// /Users/henrilepic/gocode/src/github.com/konginteractive/cme/
templatesHtml = htmlTempl.Must(htmlTempl.ParseGlob("./app/vues/*"))
templatesText = textTempl.Must(textTempl.ParseGlob("./app/vues/*"))
// permet d'avoir quelques variables
//fmt.Println("YS : " + YS + " / MS : " + MS)
}
示例6: RenderAll
func (r Renderer) RenderAll(site *SiteContext, posts []*Post) error {
templates := template.Must(
template.ParseGlob(path.Join(r.TemplatePath, "*.html")))
// ensure the output directory exists
err := os.MkdirAll(path.Join(r.OutputPath), 0755)
if err != nil {
return err
}
// copy assets
cpDir(path.Join(r.TemplatePath, "assets"), path.Join(r.OutputPath, "assets"))
// make the index page
index, err := os.Create(path.Join(r.OutputPath, "index.html"))
if err != nil {
log.Panicf(err.Error())
}
err = templates.ExecuteTemplate(index, "index.html", &IndexContext{site, posts, "Home", ""})
// gratuitous use of goroutines
// use a WaitGroup to ensure all goroutines get access to STDOUT
var wg sync.WaitGroup
for _, post := range posts {
wg.Add(1)
go func(site *SiteContext, post *Post) {
defer wg.Done()
pc := &PostContext{site, post, "../"}
r.RenderPost(pc, templates)
}(site, post)
}
wg.Wait()
return nil
}
示例7: ExampleTemplate_glob
// Here we demonstrate loading a set of templates from a directory.
func ExampleTemplate_glob() {
// Here we create a temporary directory and populate it with our sample
// template definition files; usually the template files would already
// exist in some location known to the program.
dir := createTestDir([]templateFile{
// T0.tmpl is a plain template file that just invokes T1.
{"T0.tmpl", `T0 invokes T1: ({{template "T1"}})`},
// T1.tmpl defines a template, T1 that invokes T2.
{"T1.tmpl", `{{define "T1"}}T1 invokes T2: ({{template "T2"}}){{end}}`},
// T2.tmpl defines a template T2.
{"T2.tmpl", `{{define "T2"}}This is T2{{end}}`},
})
// Clean up after the test; another quirk of running as an example.
defer os.RemoveAll(dir)
// pattern is the glob pattern used to find all the template files.
pattern := filepath.Join(dir, "*.tmpl")
// Here starts the example proper.
// T0.tmpl is the first name matched, so it becomes the starting template,
// the value returned by ParseGlob.
tmpl := template.Must(template.ParseGlob(pattern))
err := tmpl.Execute(os.Stdout, nil)
if err != nil {
log.Fatalf("template execution: %s", err)
}
// Output:
// T0 invokes T1: (T1 invokes T2: (This is T2))
}
示例8: TestSendNags
func TestSendNags(t *testing.T) {
stats, _ := statsd.NewNoopClient(nil)
mc := mocks.Mailer{}
rs := newFakeRegStore()
fc := newFakeClock(t)
m := mailer{
stats: stats,
mailer: &mc,
emailTemplate: tmpl,
subject: testEmailSubject,
rs: rs,
clk: fc,
}
cert := &x509.Certificate{
Subject: pkix.Name{
CommonName: "happy",
},
NotAfter: fc.Now().AddDate(0, 0, 2),
DNSNames: []string{"example.com"},
}
err := m.sendNags([]*core.AcmeURL{emailA}, []*x509.Certificate{cert})
test.AssertNotError(t, err, "Failed to send warning messages")
test.AssertEquals(t, len(mc.Messages), 1)
test.AssertEquals(t, mocks.MailerMessage{
To: emailARaw,
Subject: testEmailSubject,
Body: fmt.Sprintf(`hi, cert for DNS names example.com is going to expire in 2 days (%s)`, cert.NotAfter.Format(time.RFC822Z)),
}, mc.Messages[0])
mc.Clear()
err = m.sendNags([]*core.AcmeURL{emailA, emailB}, []*x509.Certificate{cert})
test.AssertNotError(t, err, "Failed to send warning messages")
test.AssertEquals(t, len(mc.Messages), 2)
test.AssertEquals(t, mocks.MailerMessage{
To: emailARaw,
Subject: testEmailSubject,
Body: fmt.Sprintf(`hi, cert for DNS names example.com is going to expire in 2 days (%s)`, cert.NotAfter.Format(time.RFC822Z)),
}, mc.Messages[0])
test.AssertEquals(t, mocks.MailerMessage{
To: emailBRaw,
Subject: testEmailSubject,
Body: fmt.Sprintf(`hi, cert for DNS names example.com is going to expire in 2 days (%s)`, cert.NotAfter.Format(time.RFC822Z)),
}, mc.Messages[1])
mc.Clear()
err = m.sendNags([]*core.AcmeURL{}, []*x509.Certificate{cert})
test.AssertNotError(t, err, "Not an error to pass no email contacts")
test.AssertEquals(t, len(mc.Messages), 0)
templates, err := template.ParseGlob("../../data/*.template")
test.AssertNotError(t, err, "Failed to parse templates")
for _, template := range templates.Templates() {
m.emailTemplate = template
err = m.sendNags(nil, []*x509.Certificate{cert})
test.AssertNotError(t, err, "failed to send nag")
}
}
示例9: WrapHandlerImpl
// Wraps other http handlers. Creates context object, recovers from panics, etc.
func WrapHandlerImpl(fn AppHandlerFunc, parseForm bool) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
c := &Context{}
// See http://blog.golang.org/2010/08/defer-panic-and-recover.html.
defer func() {
if data := recover(); data != nil {
c.Aec().Errorf(fmt.Sprint(data))
ServeError(w, data)
}
}()
// Initialize the request context object.
c.SetAec(appengine.NewContext(r))
CheckError(ReadSession(r, c))
if msg, err := ConsumeFlash(w, r); err != nil && err != http.ErrNoCookie {
ServeError(w, err)
return
} else {
c.SetFlash(msg)
}
if parseForm {
CheckError(r.ParseForm())
}
if appengine.IsDevAppServer() {
tmpl = template.Must(template.ParseGlob("templates/*.html"))
text_tmpl = text_template.Must(text_template.ParseGlob("templates/*.txt"))
}
fn(w, r, c)
}
}
示例10: init
func init() {
var err error
Templates, err = template.ParseGlob("templates/*/*.html")
if err != nil {
panic(err)
}
}
示例11: ServeServerRoutes
func ServeServerRoutes(port string, pusher *UDPush.Pusher) {
Pusher = pusher
var err error
T, err = template.ParseGlob("server/templates/*")
_ = err
r := mux.NewRouter()
r.StrictSlash(true)
// public
r.HandleFunc("/", IndexHandler)
r.HandleFunc("/login/", LoginHandler).Methods("GET")
r.HandleFunc("/sign-up/", SignUpHandler).Methods("POST")
r.HandleFunc("/file-data/{email}", FilesHandler).Methods("POST")
r.HandleFunc("/download/{id}/{filename}", DownloadHandler).Methods("GET")
// require client authentication
r.HandleFunc("/file-actions/", sessionValidate(FileActionsHandler)).Methods("POST")
r.HandleFunc("/upload/", sessionValidate(UploadHandler)).Methods("POST")
r.HandleFunc("/download/", sessionValidate(FileDownloadHandler)).Methods("POST")
r.HandleFunc("/clients/", sessionValidate(ClientsFileActionsHandler)).Methods("POST")
// static files? (css, js, etc...)
// r.PathPrefix("/").Handler(http.FileServer(http.Dir("./public/")))
http.Handle("/", r)
fmt.Println("Serving api on port :" + port)
http.ListenAndServe(":"+port, nil)
}
示例12: main
func main() {
var err error
cwd, _ := os.Getwd()
client := flag.String("client", path.Join(cwd, "client"), "Full path to client directory.")
addr := flag.String("listen", "127.0.0.1:8088", "Listen address.")
templates, err = template.ParseGlob(path.Join(*client, "*.html"))
if err != nil {
log.Fatal("Failed to load templates: ", err)
}
flag.Parse()
go h.run()
http.HandleFunc("/", serveClient)
http.HandleFunc("/realtimetraffic", serveWs)
http.Handle("/css/", http.FileServer(http.Dir(*client)))
http.Handle("/scripts/", http.FileServer(http.Dir(*client)))
http.Handle("/img/", http.FileServer(http.Dir(*client)))
http.Handle("/favicon.ico", http.FileServer(http.Dir(*client)))
err = http.ListenAndServe(*addr, nil)
if err != nil {
log.Fatal("ListenAndServe: ", err)
}
}
示例13: startup
func startup() {
loadConfig()
log.Printf("Lanyon listening on http://localhost:%d", config.PortNum)
// add trailing slashes to config directories
if !strings.HasSuffix(config.PublicDir, "/") {
config.PublicDir = config.PublicDir + "/"
}
// verify public directory exists
if _, err := os.Stat(config.PublicDir); err != nil {
log.Fatalln("Public directory does not exist")
}
// add trailing slashes to config directories
if !strings.HasSuffix(config.TemplateDir, "/") {
config.TemplateDir = config.TemplateDir + "/"
}
// verify template directory exists
if _, err := os.Stat(config.TemplateDir); err != nil {
log.Fatalln("Template directory does not exist")
}
var err error
ts, err = template.ParseGlob(config.TemplateDir + "*.html")
if err != nil {
log.Fatalln("Error Parsing Templates: ", err)
}
}
示例14: Start
func Start(conn *CGRConnector, user, pass string) {
connector = conn
username = user
password = pass
templates = template.Must(template.ParseGlob("templates/*.tmpl"))
rpc.Register(conn)
goji.Get(LOGIN_PATH, loginGet)
goji.Post(LOGIN_PATH, loginPost)
goji.Get("/app/*", http.FileServer(http.Dir("./static")))
auth := web.New()
goji.Handle("/*", auth)
auth.Use(SessionAuth)
auth.Handle("/ws", websocket.Handler(func(ws *websocket.Conn) {
jsonrpc.ServeConn(ws)
}))
auth.Post("/import/", importPost)
auth.Post("/exportcdrs/", exportCdrsPost)
auth.Post("/exporttpcsv/", exportTpToCsvPost)
auth.Get("/accounts/logout", logoutGet)
auth.Get("/", http.RedirectHandler("/app/", 301))
}
示例15: main
// ディレクトリにあるテンプレート郡をロードするデモです。
func main() {
dir := createTestDir([]templateFile{
// T0.tmpl はT1をコールします。
{"T0.tmpl", `T0 invokes T1: ({{template "T1"}})`},
// T1.tmpl T2をコールするテンプレートを"T1"として定義しています。
{"T1.tmpl", `{{define "T1"}}T1 invokes T2: ({{template "T2"}}){{end}}`},
// T2.tmpl は"T2"としてテンプレートを定義しています。
{"T2.tmpl", `{{define "T2"}}This is T2{{end}}`},
})
// main関数終了後、作成したディレクトリを削除します。
defer os.RemoveAll(dir)
// dirにあるすべてのテンプレートファイルを検索するようにパターンを作成しています。
pattern := filepath.Join(dir, "*.tmpl")
// ここから本題です。
// T0.tmpl は初めにマッチする名前ですので、始めのテンプレート(ParseGlobの戻り値の値)になります。
tmpl := template.Must(template.ParseGlob(pattern))
log.Println(tmpl.Name())
err := tmpl.Execute(os.Stdout, nil)
if err != nil {
log.Fatalf("template execution: %s", err)
}
// Output:
// T0 invokes T1: (T1 invokes T2: (This is T2))
}