예제 #1
0
파일: main.go 프로젝트: andviro/noodle
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
0
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
0
//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
0
// 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
0
파일: template.go 프로젝트: a2800276/gaml
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
0
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
0
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
0
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
0
파일: 02-internal.go 프로젝트: aerth/cosgo
// 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
0
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
0
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
0
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
0
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
0
//列出某问题的详细信息,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
0
파일: downloads-page.go 프로젝트: yl10/goxc
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
}
예제 #16
0
func init() {
	var err error
	rand.Seed(time.Now().UnixNano())

	// funcMap contains the functions available to the view template
	funcMap := template.FuncMap{
		// totals sums all the exercises in []RepData
		"totals": func(d []RepData) int {
			return totalReps(d)
		},
		// allow easy converting of strings to JS string (turns freqData{{ OfficeName}}: freqData"OC" -> freqDataOC in JS)
		"js": func(s string) template.JS {
			return template.JS(s)
		},
		// d3ChartData correctly formats []RepData to the JS format so data can display
		"d3ChartData": func(d []RepData) template.JS {
			parts := make([]string, len(d))
			for i, data := range d {
				parts[i] = fmt.Sprintf("{State:'%s',freq:{pull_up:%d, sit_up:%d, push_up: %d, squat:%d}}",
					data.Date,
					data.ExerciseCounts[PullUps],
					data.ExerciseCounts[SitUps],
					data.ExerciseCounts[PushUps],
					data.ExerciseCounts[Squats],
				)
			}
			return template.JS(strings.Join(parts, ",\n"))
		},
		// d3ChartDataForOffice is a helper method to avoid complexities with nesting ranges in the template
		"d3ChartDataForOffice": func(officeName string, reps map[string][]RepData) template.JS {
			// TODO: DRY up with ^^
			parts := make([]string, len(reps[officeName]))
			for i, data := range reps[officeName] {
				parts[i] = fmt.Sprintf("{State:'%s',freq:{pull_up:%d, sit_up:%d, push_up: %d, squat:%d}}",
					data.Date,
					data.ExerciseCounts[PullUps],
					data.ExerciseCounts[SitUps],
					data.ExerciseCounts[PushUps],
					data.ExerciseCounts[Squats],
				)
			}
			return template.JS(strings.Join(parts, ",\n"))
		},
	}

	// parse tempaltes in init so we don't have to parse them on each request
	// pro: single parsing
	// con: have to restart the process to load file changes
	ViewTemplate, err = template.New("view.html").Funcs(funcMap).ParseFiles(filepath.Join("go_templates", "view.html"))
	if err != nil {
		log.Fatalln(err)
	}

	IndexTemplate, err = template.New("index.html").Funcs(funcMap).ParseFiles(filepath.Join("go_templates", "index.html"))
	if err != nil {
		log.Fatalln(err)
	}

}
예제 #17
0
파일: main.go 프로젝트: composehub/server
func init() {
	Dev = os.Getenv("DEV")
	funcs := template.FuncMap{
		"inc":      inc,
		"split":    split,
		"gravatar": gravatar,
		"timeAgo":  timeAgo,
		"markDown": markDowner,
	}
	T["index.html"], _ = template.New("base.html").Funcs(funcs).ParseFiles("assets/index.html", "assets/base.html")
	T["search.html"], _ = template.New("base.html").Funcs(funcs).ParseFiles("assets/search.html", "assets/base.html")
	T["package.html"], _ = template.New("base.html").Funcs(funcs).ParseFiles("assets/package.html", "assets/base.html")
	T["user.html"], _ = template.New("base.html").Funcs(funcs).ParseFiles("assets/user.html", "assets/base.html")

	//T["package.html"] = template.Must(template.ParseFiles("assets/package.html", "assets/base.html"))
	//T["user.html"] = template.Must(template.ParseFiles("assets/user.html", "assets/base.html"))
	//T["user.html"] = setFuncs(T["user.html"])
	//T["package.html"] = setFuncs(T["package.html"])

	DbUser = os.Getenv("")
	DbPass = os.Getenv("COMPOSITOR_DB_1_ENV_MYSQL_ROOT_PASSWORD")
	DbURL = os.Getenv("COMPOSITOR_DB_1_PORT_3306_TCP_ADDR")
	DbName = os.Getenv("COMPOSITOR_DB_1_ENV_MYSQL_DATABASE")
	if DbUser == "" {
		DbUser = "******"
	}
	if DbPass == "" {
		DbPass = "******"
	}
	if DbName == "" {
		DbName = "composehub"
	}
	if DbURL == "" {
		DbURL = "localhost"
	}
	db, err := gorm.Open("mysql", DbUser+":"+DbPass+"@tcp("+DbURL+":3306)/"+DbName+"?charset=utf8mb4&parseTime=True&loc=Local")
	if err != nil {
		devlog(DbUser + ":" + DbPass + "@" + DbURL + "/" + DbName + "?charset=utf8mb4&parseTime=True&loc=Local")
		log.Fatalln(err)
	}
	/*db.Exec("CREATE DATABASE if not exists `" + DbName + "` CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci")*/
	/*err = db.Exec("USE " + DbName).Error*/
	/*if err != nil {*/
	/*panic(err)*/
	/*}*/
	db.DB()
	DB = db
	if Dev != "" {
		DB.LogMode(true)
	}

	DB.AutoMigrate(&User{})
	DB.AutoMigrate(&Package{})
	DB.AutoMigrate(&Download{})
	DB.Exec("alter table packages add unique index(name);")
	DB.Exec("alter table users add unique index(email);")
	DB.Exec("alter table users add unique index(handle);")
	R = render.New(render.Options{})
}
예제 #18
0
파일: web.go 프로젝트: GREsau/MailHog-UI
func (web Web) Index() func(http.ResponseWriter, *http.Request) {
	tmpl := template.New("index.html")
	tmpl.Delims("[:", ":]")

	asset, err := web.asset("assets/templates/index.html")
	if err != nil {
		log.Fatalf("[UI] Error loading index.html: %s", err)
	}

	tmpl, err = tmpl.Parse(string(asset))
	if err != nil {
		log.Fatalf("[UI] Error parsing index.html: %s", err)
	}

	layout := template.New("layout.html")
	layout.Delims("[:", ":]")

	asset, err = web.asset("assets/templates/layout.html")
	if err != nil {
		log.Fatalf("[UI] Error loading layout.html: %s", err)
	}

	layout, err = layout.Parse(string(asset))
	if err != nil {
		log.Fatalf("[UI] Error parsing layout.html: %s", err)
	}

	return func(w http.ResponseWriter, req *http.Request) {
		data := map[string]interface{}{
			"config":  web.config,
			"Page":    "Browse",
			"APIHost": APIHost,
		}

		b := new(bytes.Buffer)
		err := tmpl.Execute(b, data)

		if err != nil {
			log.Printf("[UI] Error executing template: %s", err)
			w.WriteHeader(500)
			return
		}

		data["Content"] = template.HTML(b.String())

		b = new(bytes.Buffer)
		err = layout.Execute(b, data)

		if err != nil {
			log.Printf("[UI] Error executing template: %s", err)
			w.WriteHeader(500)
			return
		}

		w.Header().Set("Content-Type", "text/html; charset=utf-8")
		w.WriteHeader(200)
		w.Write(b.Bytes())
	}
}
예제 #19
0
func main() {
	t := template.New("test")
	t = template.Must(t.Parse("{{with $3:=`ok`}}{{$3}}\n{{end}}"))
	t.Execute(os.Stdout, nil)
	t = template.New("test1")
	t = template.Must(t.Parse("{{with $4:=`123`}}{{$4}}\n{{end}}"))
	t.Execute(os.Stdout, nil)
}
예제 #20
0
파일: server.go 프로젝트: HeWhoWas/mokey
func NewApplication() (*Application, error) {
	db, err := NewDb()
	if err != nil {
		return nil, err
	}

	tmpldir := viper.GetString("templates")
	if len(tmpldir) == 0 {
		// default to directory of current executable
		path, err := filepath.EvalSymlinks(os.Args[0])
		if err != nil {
			log.Fatal(err)
		}
		dir, err := filepath.Abs(filepath.Dir(path))
		if err != nil {
			log.Fatal(err)
		}
		tmpldir = dir + "/templates"
	}

	logrus.Printf("Using template dir: %s", tmpldir)

	tmpls, err := filepath.Glob(tmpldir + "/*.html")
	if err != nil {
		log.Fatal(err)
	}

	templates := make(map[string]*template.Template)
	for _, t := range tmpls {
		base := filepath.Base(t)
		if base != "layout.html" {
			templates[base] = template.Must(template.New("layout").ParseFiles(t,
				tmpldir+"/layout.html"))
		}
	}

	tmpls, err = filepath.Glob(tmpldir + "/email/*.txt")
	if err != nil {
		log.Fatal(err)
	}

	emails := make(map[string]*template.Template)
	for _, t := range tmpls {
		base := filepath.Base(t)
		emails[base] = template.Must(template.New(base).ParseFiles(t))
	}

	app := &Application{}
	app.tmpldir = tmpldir
	app.db = db
	app.cookieStore = sessions.NewCookieStore([]byte(viper.GetString("secret_key")))
	app.decoder = schema.NewDecoder()
	//app.decoder.IgnoreUnknownKeys(true)
	app.templates = templates
	app.emails = emails

	return app, nil
}
예제 #21
0
파일: init.go 프로젝트: Blurmint199/Lycos
func init() {
	if b, err := ioutil.ReadFile(characterSettingFilePath); err == nil {
		if err = yaml.Unmarshal(b, &characterSet); err != nil {
			panic(err)
		}
		// Check Mistakes
		if len(characterSet) == 0 {
			panic(characterSettingFilePath + " is empty!")
		}
		for i := range characterSet {
			if characterSet[i].File == "" || characterSet[i].Name == "" {
				panic(characterSettingFilePath + " has Empty Element")
			}
		}
	} else {
		panic("Please Setup your " + characterSettingFilePath)
	}

	if b, err := ioutil.ReadFile(textSettingFilePath); err == nil {
		if err = yaml.Unmarshal(b, &setting); err != nil {
			panic(err)
		}
	} else {
		panic("Please Setup your " + textSettingFilePath +
			" if you don't want change from default setting, please reset this file.")
	}

	tf := template.FuncMap{
		"rawhtml": func(text string) template.HTML { return template.HTML(text) },
		"up":      func(i int) int { return i + 1 },
		"showNumberTag": func(tag string) string {
			if tag == "" {
				return ""
			} else {
				return "(No." + tag + ")"
			}
		},
	}
	topTmpl = template.Must(template.New("").Funcs(tf).ParseFiles("templates/top.html"))
	createPageTmpl = template.Must(template.New("").Funcs(tf).ParseFiles("templates/create.html"))
	villagePageTmpl = template.Must(template.New("").Funcs(tf).ParseFiles("templates/village.html"))
	prewriteTmpl = template.Must(template.New("").Funcs(tf).ParseFiles("templates/prewrite.html"))
	badTmpl = template.Must(template.New("").Funcs(tf).ParseFiles("templates/badreq.html"))

	http.HandleFunc("/", topHandler)
	http.HandleFunc("/village/", villageHandler)
	http.HandleFunc("/prewrite", villagePreWriteHandler)
	http.HandleFunc("/write", villagePostWriteHandler)
	http.HandleFunc("/enter", enterToVillageHandler)
	http.HandleFunc("/create", createPageHandler)
	http.HandleFunc("/rename", renameHandler)
	http.HandleFunc("/build", buildPageHandler)
	http.HandleFunc("/vote", changeVoteTargetHandler)
	http.HandleFunc("/change", changeAbilityTargetHandler)
	http.HandleFunc("/start/", villageStartHandler)
	http.HandleFunc("/update", updateHandler)
}
예제 #22
0
파일: func_map.go 프로젝트: 8legd/qor-qor
func (context *Context) RenderMeta(meta *Meta, value interface{}, prefix []string, metaType string, writer *bytes.Buffer) {
	prefix = append(prefix, meta.Name)

	funcsMap := context.FuncMap()
	funcsMap["render_form"] = func(value interface{}, sections []*Section, index ...int) template.HTML {
		var result = bytes.NewBufferString("")
		newPrefix := append([]string{}, prefix...)

		if len(index) > 0 {
			last := newPrefix[len(newPrefix)-1]
			newPrefix = append(newPrefix[:len(newPrefix)-1], fmt.Sprintf("%v[%v]", last, index[0]))
		}

		for _, field := range context.GetDB().NewScope(value).PrimaryFields() {
			if meta := sections[0].Resource.GetMetaOrNew(field.Name); meta != nil {
				context.RenderMeta(meta, value, newPrefix, "form", result)
			}
		}

		context.renderForm(value, sections, newPrefix, result)

		return template.HTML(result.String())
	}

	var tmpl *template.Template
	var err error
	if file, err := context.FindTemplate(fmt.Sprintf("metas/%v/%v.tmpl", metaType, meta.Name), fmt.Sprintf("metas/%v/%v.tmpl", metaType, meta.Type)); err == nil {
		tmpl, err = template.New(filepath.Base(file)).Funcs(funcsMap).ParseFiles(file)
	} else {
		tmpl, err = template.New(meta.Type + ".tmpl").Funcs(funcsMap).Parse("{{.Value}}")
	}

	if err == nil {
		var scope = context.GetDB().NewScope(value)
		var data = map[string]interface{}{
			"Context":       context,
			"BaseResource":  meta.baseResource,
			"ResourceValue": value,
			"InputId":       fmt.Sprintf("%v_%v_%v", scope.GetModelStruct().ModelType.Name(), scope.PrimaryKeyValue(), meta.Name),
			"Label":         meta.Label,
			"InputName":     strings.Join(prefix, "."),
			"Value":         context.FormattedValueOf(value, meta),
			"Meta":          meta,
		}

		if meta.GetCollection != nil {
			data["CollectionValue"] = meta.GetCollection(value, context.Context)
		}

		err = tmpl.Execute(writer, data)
	}

	if err != nil {
		utils.ExitWithMsg(fmt.Sprintf("got error when render %v template for %v(%v):%v", metaType, meta.Name, meta.Type, err))
	}
}
예제 #23
0
파일: pages.go 프로젝트: zephyyrr/authprox
func (tr *TemplateRenderer) Load() {
	if tr.Dir == "" {
		tr.Template = template.New("default.tmpl.html")
		template.Must(tr.Parse(pageTemplate))
	} else {
		tr.Template = template.New("_")
		template.Must(tr.ParseGlob(filepath.Join(tr.Dir, "*.tmpl.html")))
	}

}
예제 #24
0
파일: fedex.go 프로젝트: scottcagno/net_kit
func NewShipment(shipper, recipient Contact) *Shipment {
	return &Shipment{
		Account:         Acct,
		Shipper:         shipper,
		Recipient:       recipient,
		RequestTemplate: template.Must(template.New("xml").Parse(REQUEST_SHIPMENT_XML)),
		TagTemplate:     template.Must(template.New("tag").Parse(`<img width="380" hspace="25" vspace="50" src="data:image/png;base64,{{ .tag }}">`)),
		Timestamp:       time.Now(),
	}
}
예제 #25
0
func main() {
	tmpl := template.Must(template.New("m1").Parse(mone))
	tmpl = template.Must(tmpl.New("m2").Parse(mtwo))
	tmpl = template.Must(template.New("all").Parse(mall))

	err := tmpl.Execute(os.Stdout, nil)
	if err != nil {
		panic(err)
	}
}
예제 #26
0
func BuildTemplate(templateName string) *template.Template {
	pageTemplate, err := template.New(templateName).ParseFiles("templates/top.html", "templates/bottom.html", "templates/"+templateName)
	if err != nil {
		pageTemplate, err = template.New("Error").Parse("Oops! Didn't see that one coming.")
		if err != nil {
			panic(err)
		}
	}
	return pageTemplate
}
예제 #27
0
func loadWithRootFallback(templateName, controllerName string, helpers template.FuncMap) (*template.Template, error) {
	t, err := template.New(templateName + ".html").Funcs(helpers).ParseFiles(templatePath(controllerName, templateName))
	if err != nil {
		t, err = template.New(templateName + ".html").Funcs(helpers).ParseFiles(templatePath(templateName))
		if err != nil {
			return nil, err
		}
	}
	return t, nil
}
예제 #28
0
파일: forms.go 프로젝트: scottcagno/net_kit
func init() {
	var FUNCS = template.FuncMap{
		"safe": func(s string) template.HTMLAttr {
			return template.HTMLAttr(s)
		},
	}
	DEFAULT = template.Must(template.New("form").Funcs(FUNCS).Parse(DEFAULT_FORM))
	INLINE = template.Must(template.New("form").Funcs(FUNCS).Parse(INLINE_FORM))
	PARTIAL = template.Must(template.New("form").Funcs(FUNCS).Parse(PARTIAL_FORM))
}
예제 #29
0
func setup() *Confirm {
	ab := authboss.New()
	ab.Storer = mocks.NewMockStorer()
	ab.LayoutHTMLEmail = template.Must(template.New("").Parse(`email ^_^`))
	ab.LayoutTextEmail = template.Must(template.New("").Parse(`email`))

	c := &Confirm{}
	if err := c.Initialize(ab); err != nil {
		panic(err)
	}
	return c
}
예제 #30
0
파일: web.go 프로젝트: yujinqiu/gotrace
func init() {
	devMode = os.Getenv("GOTRACE_DEVMODE") == "1"
	if devMode {
		indexTmpl = template.Must(template.New("index.html").Parse("page/index.html"))
	} else {
		data, err := Asset("page/index.html")
		if err != nil {
			panic(err)
		}
		indexTmpl = template.Must(template.New("index.html").Parse(string(data)))
	}
}