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


Golang template.ParseGlob函数代码示例

本文整理汇总了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))
}
开发者ID:ieyasu,项目名称:go-bwiki,代码行数:29,代码来源:wiki.go

示例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)
	}
}
开发者ID:GoesToEleven,项目名称:golang-web,代码行数:26,代码来源:main.go

示例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
}
开发者ID:thesoftwarefactoryuk,项目名称:podbaby,代码行数:7,代码来源:mailer.go

示例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,
	}
}
开发者ID:hooblei,项目名称:goven,代码行数:31,代码来源:site.go

示例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)
}
开发者ID:konginteractive,项目名称:cme,代码行数:7,代码来源:render.go

示例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
}
开发者ID:visualmotive,项目名称:gobig,代码行数:35,代码来源:gobig.go

示例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))
}
开发者ID:strongo,项目名称:templates,代码行数:31,代码来源:examplefiles_test.go

示例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")
	}
}
开发者ID:MTRNord,项目名称:boulder-freifunk_support,代码行数:60,代码来源:main_test.go

示例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)
	}
}
开发者ID:asadovsky,项目名称:tadue,代码行数:34,代码来源:util.go

示例10: init

func init() {
	var err error
	Templates, err = template.ParseGlob("templates/*/*.html")
	if err != nil {
		panic(err)
	}
}
开发者ID:bxd,项目名称:gowebapp,代码行数:7,代码来源:templates.go

示例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)
}
开发者ID:vichetuc,项目名称:gobox,代码行数:29,代码来源:api.go

示例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)
	}

}
开发者ID:ngaut,项目名称:realtimetraffic,代码行数:28,代码来源:main.go

示例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)
	}

}
开发者ID:jordic,项目名称:lanyon,代码行数:31,代码来源:main.go

示例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))
}
开发者ID:MartinChenjq,项目名称:cgradmin,代码行数:25,代码来源:cgradmin.go

示例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))
}
开发者ID:kwmt,项目名称:golangwiki,代码行数:28,代码来源:exampletemplate_glob.go


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