Golang HTML示例

说明

golang html示例是从最受好评的开源项目中提取的实现代码,你可以参考下面示例的使用方式。

编程语言: Golang

命名空间/包名称: html/template

示例#1
文件: plugin.go 项目: diegobernardes/gowebapp

// TemplateFuncMap returns a map of functions that are usable in templates
func TemplateFuncMap() template.FuncMap {
	v := config.Raw.View
	f := make(template.FuncMap)

	f["JS"] = func(s string) template.HTML {
		path, err := v.AssetTimePath(s)

		if err != nil {
			log.Println("JS Error:", err)
			return template.HTML("<!-- JS Error: " + s + " -->")
		}

		return template.HTML(`<script type="text/javascript" src="` + path + `"></script>`)
	}

	f["CSS"] = func(s string) template.HTML {
		path, err := v.AssetTimePath(s)

		if err != nil {
			log.Println("CSS Error:", err)
			return template.HTML("<!-- CSS Error: " + s + " -->")
		}

		return template.HTML(`<link rel="stylesheet" type="text/css" href="` + path + `" />`)
	}

	f["LINK"] = func(path, name string) template.HTML {
		return template.HTML(`<a href="` + v.PrependBaseURI(path) + `">` + name + `</a>`)
	}

	return f
}

示例#2
文件: feed.go 项目: rcarmo/go-rss2imap

func itemToBody(feed *feedparser.Feed, item *feedparser.FeedItem) io.Reader {

	tmpl := template.Must(template.New("message").Parse(ctx.Template))

	type tmplData struct {
		Link    string
		Title   string
		Author  string
		Content template.HTML
	}

	data := tmplData{
		Link:  item.Link,
		Title: item.Title,
	}

	if len(item.Content) > 0 {
		data.Content = template.HTML(item.Content)
	} else {
		data.Content = template.HTML(item.Description)
	}

	var doc bytes.Buffer
	tmpl.Execute(&doc, data)
	return &doc
}

示例#3
文件: web.go 项目: mehulsbhatt/kb

// Base handler for HTTP requests.
func (*handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	path := r.URL.Path

	if strings.HasPrefix(path, "/css/") {
		path = strings.TrimLeft(path, "/css/")
		if css, ok := assets.Css[path]; ok {
			w.Header().Set("Content-Type", "text/css; charset=utf-8")
			w.Write([]byte(css))
		} else {
			w.WriteHeader(http.StatusNotFound)
		}
	} else if path == "/favicon.ico" {
	} else {
		var file []byte

		path = strings.TrimLeft(path, "/")
		if path == "" {
			file = markdown.GetReadme()
		} else {
			file = markdown.GetFile(path)
		}
		data := data{
			Title:   "Knowledge Base",
			Index:   template.HTML(string(markdown.GetIndex())),
			Content: template.HTML(string(file)),
		}
		render(w, data)
	}
}

示例#4
文件: build_baron.go 项目: IanWhalen/build-baron-plugin

func (bbp *BuildBaronPlugin) GetPanelConfig() (*plugin.PanelConfig, error) {
	root := plugin.StaticWebRootFromSourceFile()
	panelHTML, err := ioutil.ReadFile(root + "/partials/ng_include_task_build_baron.html")
	if err != nil {
		return nil, fmt.Errorf("Can't load panel html file, %v, %v",
			root+"/partials/ng_include_task_build_baron.html", err)
	}

	includeJS, err := ioutil.ReadFile(root + "/partials/script_task_build_baron_js.html")
	if err != nil {
		return nil, fmt.Errorf("Can't load panel html file, %v, %v",
			root+"/partials/script_task_build_baron_js.html", err)
	}

	includeCSS, err := ioutil.ReadFile(root +
		"/partials/link_task_build_baron_css.html")
	if err != nil {
		return nil, fmt.Errorf("Can't load panel html file, %v, %v",
			root+"/partials/link_task_build_baron_css.html", err)
	}

	return &plugin.PanelConfig{
		StaticRoot: plugin.StaticWebRootFromSourceFile(),
		Panels: []plugin.UIPanel{
			{
				Page:      plugin.TaskPage,
				Position:  plugin.PageRight,
				PanelHTML: template.HTML(panelHTML),
				Includes:  []template.HTML{template.HTML(includeCSS), template.HTML(includeJS)},
			},
		},
	}, nil
}

示例#5
文件: template.go 项目: Palats/stdweb

func (t *Template) render(rctx core.RenderContext) string {
	b := &bytes.Buffer{}

	// Update functions for current rendering context.
	t.tmpl.Funcs(map[string]interface{}{
		"slot": func(name, elt string) template.HTML {
			s := t.node.Slot(name)
			if elt == "" {
				return template.HTML(s.Node().Render(rctx))
			}
			return template.HTML(fmt.Sprintf("<%s id='%s'>%s</%s>", elt, s.ID(), s.Node().Render(rctx), elt))
		},
		"event": func(name string) template.JS {
			return template.JS(fmt.Sprintf("stdweb.events.onClick('%s', '%s', event)", template.JSEscapeString(t.node.ID()), template.JSEscapeString(name)))
		},
	})

	err := t.tmpl.Execute(b, &tplData{
		ID:       t.node.ID(),
		RunID:    rctx.RunID(),
		UpdateID: rctx.UpdateID(),
		Data:     t.data,
	})

	if err == nil {
		return b.String()
	}
	return html.EscapeString(err.Error())
}

示例#6
文件: template.go 项目: no2key/her

func templateFuncMap() template.FuncMap {
	return template.FuncMap{
		"set": func(renderArgs map[string]interface{}, key string, value interface{}) template.HTML {
			renderArgs[key] = value
			return template.HTML("")
		},
		"append": func(renderArgs map[string]interface{}, key string, value interface{}) template.HTML {
			if renderArgs[key] == nil {
				renderArgs[key] = []interface{}{value}
			} else {
				renderArgs[key] = append(renderArgs[key].([]interface{}), value)
			}
			return template.HTML("")
		},
		// Replaces newlines with <br>
		"nl2br": func(text string) template.HTML {
			return template.HTML(strings.Replace(template.HTMLEscapeString(text), "\n", "<br>", -1))
		},
		// Skips sanitation on the parameter.  Do not use with dynamic data.
		"raw": func(text string) template.HTML {
			return template.HTML(text)
		},
		"datetime": func(date time.Time, format string) string {
			return date.Format(format)
		},
	}
}

示例#7
文件: page.go 项目: hugoduncan/hugo

func (page *Page) convertMarkdown(lines io.Reader) {
	b := new(bytes.Buffer)
	b.ReadFrom(lines)
	content := string(blackfriday.MarkdownCommon(b.Bytes()))
	page.Content = template.HTML(content)
	page.Summary = template.HTML(TruncateWordsToWholeSentence(StripHTML(StripShortcodes(content)), summaryLength))
}

示例#8
文件: xmlreader.go 项目: speedata/ltxdoc

func readDescription(attributes []xml.Attr, dec *xml.Decoder) (string, template.HTML) {
	var lang string
	for _, attribute := range attributes {
		if attribute.Name.Local == "lang" {
			lang = attribute.Value
		}
	}
	var str string
	for {

		t, err := dec.Token()
		if err != nil {
			break
		}
		switch v := t.(type) {
		case xml.CharData:
			str += string(v)
		case xml.EndElement:
			return lang, template.HTML(str)
		default:
		}
	}
	// never reached!?!?
	return lang, template.HTML(str)
}

示例#9
文件: problem.go 项目: NUOG/GoOnlineJudge

func (pc *AdminProblem) problem() (one model.Problem) {
	one.Title = pc.Input.Get("title")
	time, err := strconv.Atoi(pc.Input.Get("time"))
	if err != nil {
		pc.Error("The value 'Time' is neither too short nor too large", 400)
		return
	}
	one.Time = time
	memory, err := strconv.Atoi(pc.Input.Get("memory"))
	if err != nil {
		pc.Error("The value 'Memory' is neither too short nor too large", 400)
		return
	}
	one.Memory = memory
	if _, ok := pc.Input["special"]; !ok {
		one.Special = 0
	} else {
		one.Special = 1
	}

	in := pc.Input.Get("in")
	out := pc.Input.Get("out")
	one.Description = template.HTML(pc.Input.Get("description"))
	one.Input = template.HTML(pc.Input.Get("input"))
	one.Output = template.HTML(pc.Input.Get("output"))
	one.In = in
	one.Out = out
	one.Source = pc.Input.Get("source")
	one.Hint = template.HTML(pc.Input.Get("hint"))
	one.Status = config.StatusReverse
	one.ROJ = "ZJGSU"

	return one
}

示例#10
文件: templatefunc.go 项目: jamesbjackson/seagull

// render object to form html.
// obj must be a struct pointer.
func RenderForm(obj interface{}) template.HTML {
	objT := reflect.TypeOf(obj)
	objV := reflect.ValueOf(obj)
	if !isStructPtr(objT) {
		return template.HTML("")
	}
	objT = objT.Elem()
	objV = objV.Elem()

	var raw []string
	for i := 0; i < objT.NumField(); i++ {
		fieldV := objV.Field(i)
		if !fieldV.CanSet() || unKind[fieldV.Kind()] {
			continue
		}

		fieldT := objT.Field(i)

		label, name, fType, id, class, ignored := parseFormTag(fieldT)
		if ignored {
			continue
		}

		raw = append(raw, renderFormField(label, name, fType, fieldV.Interface(), id, class))
	}
	return template.HTML(strings.Join(raw, "</br>"))
}

示例#11
文件: order_ording.go 项目: jacobxk/go2o

func (this *orderC) setState(ctx *web.Context,
	partnerId int, order *shopping.ValueOrder) {

	var descript string
	var button string

	switch order.Status {
	case enum.ORDER_COMPLETED:
		descript = `<span style="color:green">订单已经完成!</span>`
	case enum.ORDER_CANCEL:
		descript = `<span style="color:red">订单已经作废!</span>`
	case enum.ORDER_WAIT_CONFIRM:
		descript = "确认订单无误后,点击按钮进行下一步.."
		button = `<input class="btn" type="button" id="btn2" value="确认订单"/>`
	case enum.ORDER_WAIT_DELIVERY:
		button = `<input class="btn" type="button" id="btn2" value="开始配送"/>`
	case enum.ORDER_WAIT_RECEIVE:
		button = `<input class="btn" type="button" id="btn2" value="确认收货"/>`
	case enum.ORDER_RECEIVED:
		if order.IsPaid == 0 {
			descript = `<span style="color:red">订单尚未付款,如果已经付款,请人工手动付款!</span>`
		} else {
			descript = "如果已收货,点击按钮完成订单"
			button = `<input class="btn" type="button" id="btn2" value="完成订单"/>`
		}
	}

	ctx.App.Template().Execute(ctx.Response,
		gof.TemplateDataMap{
			"button":   template.HTML(button),
			"descript": template.HTML(descript),
			"order_no": order.OrderNo,
		}, "views/partner/order/order_setup_setstate.html")
}

示例#12
文件: Pagination.go 项目: pmljm/MessageBlog

// 在页面显示分页信息, 内容为 上一页 当前页/下一页 下一页
func (p *Pagination) Html(number int) template.HTML {
	pageCount := int(math.Ceil(float64(p.count) / float64(p.prePage)))

	if pageCount <= 1 {
		return template.HTML("")
	}

	linkFlag := "?"

	if strings.Index(p.url, "?") > -1 {
		linkFlag = "&"
	}

	html := `<ul class="pager">`
	if number > 1 {
		html += fmt.Sprintf(`<li class="previous"><a href="%s%sp=%d">← 上一页</a></li>`, p.url, linkFlag, number-1)
	}

	html += fmt.Sprintf(`<li class="number">%d/%d</li>`, number, pageCount)

	if number < pageCount {
		html += fmt.Sprintf(`<li class="next"><a href="%s%sp=%d">下一页 →</a></li>`, p.url, linkFlag, number+1)
	}

	return template.HTML(html)
}

示例#13
文件: post.go 项目: cnhans/pugo-static

// post's preview html,
// use "<!--more-->" to separate, return first part
func (p *Post) PreviewHTML() template.HTML {
	bytes := bytes.Split(p.Raw, []byte("<!--more-->"))[0]
	if p.rawType == "markdown" {
		return template.HTML(helper.Markdown(bytes))
	}
	return template.HTML(bytes)
}

示例#14
文件: handlers.go 项目: billyboar/GCSolutions

func renderIndex(context *common.AppContext, userWrapper, uploadedFlag interface{}) []byte {
	// Generate the markup for the index template.
	if userWrapper == nil {
		context.Log.Print("Attempting to render the login template")
		markup := executeTemplate(context, "login", nil)
		if markup == nil {
			return nil
		}
		params := map[string]interface{}{"LayoutContent": template.HTML(string(markup))}
		return executeTemplate(context, "head", params)
	} else if uploadedFlag == nil {
		context.Log.Print("Attempting to render the upload template")
		markup := executeTemplate(context, "upload", nil)
		if markup == nil {
			return nil
		}
		params := map[string]interface{}{"LayoutContent": template.HTML(string(markup))}
		return executeTemplate(context, "head", params)
	}
	context.Log.Print("Attempting to render the search template")
	markup := executeTemplate(context, "search", nil)
	if markup == nil {
		return nil
	}
	params := map[string]interface{}{"LayoutContent": template.HTML(string(markup))}
	return executeTemplate(context, "head", params)
}

示例#15
文件: srv_topo_server.go 项目: pranjal5215/vitess

// StatusAsHTML returns an HTML version of our status.
// It works best if there is data in the cache.
func (st *SrvKeyspaceCacheStatus) StatusAsHTML() template.HTML {
	if st.Value == nil {
		return template.HTML("No Data")
	}

	result := "<b>Partitions:</b><br>"
	for tabletType, keyspacePartition := range st.Value.Partitions {
		result += " <b>" + string(tabletType) + "</b>"
		for _, shard := range keyspacePartition.ShardReferences {
			result += " " + shard.Name
		}
		result += "<br>"
	}

	if st.Value.ShardingColumnName != "" {
		result += "<b>ShardingColumnName:</b> " + st.Value.ShardingColumnName + "<br>"
		result += "<b>ShardingColumnType:</b> " + string(st.Value.ShardingColumnType) + "<br>"
	}

	if len(st.Value.ServedFrom) > 0 {
		result += "<b>ServedFrom:</b><br>"
		for tabletType, keyspace := range st.Value.ServedFrom {
			result += " <b>" + string(tabletType) + "</b> " + keyspace + "<br>"
		}
	}

	return template.HTML(result)
}

示例#16
文件: forms.go 项目: thuongdinh/beegowebapp

func init() {
	// a example to create a bootstrap style checkbox creater
	RegisterFieldCreater("checkbox", func(fSet *FieldSet) {
		value := false
		if b, ok := fSet.Value.(bool); ok {
			value = b
		}
		active := ""
		if value {
			active = " active"
		}
		fSet.Field = template.HTML(fmt.Sprintf(`<label>
            <input type="hidden" name="%s" value="%v">
            <button type="button" data-toggle="button" data-name="%s" class="btn btn-default btn-xs btn-checked%s">
            	<i class="icon icon-ok"></i>
        	</button>%s
        </label>`, fSet.Name, value, fSet.Name, active, fSet.LabelText))
	})

	// a example to create a select2 box
	RegisterFieldFilter("select", func(fSet *FieldSet) {
		if strings.Index(fSet.Attrs, `rel="select2"`) != -1 {
			field := string(fSet.Field)
			field = strings.Replace(field, "<option", "<option></option><option", 1)
			fSet.Field = template.HTML(field)
		}
	})
}

示例#17
文件: controller.go 项目: robgssp/movienet

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()))
}

示例#18
文件: manifest.go 项目: soulware/rack

func (mb ManifestBalancer) LoadBalancerName() template.HTML {
	// Bound apps do not use the StackName directly and ignore Entry.primary
	// and use AppName-EntryName-RackAppEntryHash format
	if mb.Entry.app != nil && mb.Entry.app.IsBound() {
		hash := sha256.Sum256([]byte(fmt.Sprintf("%s:%s:%s", os.Getenv("RACK"), mb.Entry.app.Name, mb.Entry.Name)))
		prefix := fmt.Sprintf("%s-%s", mb.Entry.app.Name, mb.Entry.Name)
		suffix := "-" + base32.StdEncoding.EncodeToString(hash[:])[:7]
		if !mb.Public {
			suffix += "-i"
		}
		// ELB name must be 32 chars or less
		if len(prefix) > 32-len(suffix) {
			prefix = prefix[:32-len(suffix)]
		}
		return template.HTML(`"` + prefix + suffix + `"`)
	}

	// Unbound apps use legacy StackName or StackName-ProcessName format
	if mb.Entry.primary {
		return template.HTML(`{ "Ref": "AWS::StackName" }`)
	}

	if mb.Public {
		return template.HTML(fmt.Sprintf(`{ "Fn::Join": [ "-", [ { "Ref": "AWS::StackName" }, "%s" ] ] }`, mb.ProcessName()))
	}

	return template.HTML(fmt.Sprintf(`{ "Fn::Join": [ "-", [ { "Ref": "AWS::StackName" }, "%s", "i" ] ] }`, mb.ProcessName()))
}

示例#19
文件: controller.go 项目: astaxie/beego

// RenderBytes returns the bytes of rendered template string. Do not send out response.
func (c *Controller) RenderBytes() ([]byte, error) {
	buf, err := c.renderTemplate()
	//if the controller has set layout, then first get the tplName's content set the content to the layout
	if err == nil && c.Layout != "" {
		c.Data["LayoutContent"] = template.HTML(buf.String())

		if c.LayoutSections != nil {
			for sectionName, sectionTpl := range c.LayoutSections {
				if sectionTpl == "" {
					c.Data[sectionName] = ""
					continue
				}
				buf.Reset()
				err = ExecuteTemplate(&buf, sectionTpl, c.Data)
				if err != nil {
					return nil, err
				}
				c.Data[sectionName] = template.HTML(buf.String())
			}
		}

		buf.Reset()
		ExecuteTemplate(&buf, c.Layout, c.Data)
	}
	return buf.Bytes(), err
}

示例#20
文件: markdown.go 项目: harboe/flsmidth

func GetMarkdown(file string) template.HTML {
	if input, err := ioutil.ReadFile(file); err == nil {
		return template.HTML(blackfriday.MarkdownCommon(input))
	}

	return template.HTML(" ")
}

示例#21
文件: pagination_test.go 项目: tarsisazevedo/hugo

func doTestPages(t *testing.T, paginator *paginator) {

	paginatorPages := paginator.Pagers()

	assert.Equal(t, 5, len(paginatorPages))
	assert.Equal(t, 21, paginator.TotalNumberOfElements())
	assert.Equal(t, 5, paginator.PageSize())
	assert.Equal(t, 5, paginator.TotalPages())

	first := paginatorPages[0]
	assert.Equal(t, template.HTML("page/1/"), first.URL())
	assert.Equal(t, first, first.First())
	assert.True(t, first.HasNext())
	assert.Equal(t, paginatorPages[1], first.Next())
	assert.False(t, first.HasPrev())
	assert.Nil(t, first.Prev())
	assert.Equal(t, 5, first.NumberOfElements())
	assert.Equal(t, 1, first.PageNumber())

	third := paginatorPages[2]
	assert.True(t, third.HasNext())
	assert.True(t, third.HasPrev())
	assert.Equal(t, paginatorPages[1], third.Prev())

	last := paginatorPages[4]
	assert.Equal(t, template.HTML("page/5/"), last.URL())
	assert.Equal(t, last, last.Last())
	assert.False(t, last.HasNext())
	assert.Nil(t, last.Next())
	assert.True(t, last.HasPrev())
	assert.Equal(t, 1, last.NumberOfElements())
	assert.Equal(t, 5, last.PageNumber())
}

示例#22
文件: site.go 项目: hugoduncan/hugo

func (s *Site) RenderLists() error {
	for section, data := range s.Sections {
		n := s.NewNode()
		n.Title = strings.Title(inflect.Pluralize(section))
		n.Url = Urlize(section + "/" + "index.html")
		n.Permalink = template.HTML(MakePermalink(string(n.Site.BaseUrl), string(n.Url)))
		n.RSSlink = template.HTML(MakePermalink(string(n.Site.BaseUrl), string(section+".xml")))
		n.Date = data[0].Date
		n.Data["Pages"] = data
		layout := "indexes" + slash + section + ".html"

		x, err := s.RenderThing(n, layout)
		if err != nil {
			return err
		}
		s.WritePublic(section+slash+"index.html", x.Bytes())

		if a := s.Tmpl.Lookup("rss.xml"); a != nil {
			// XML Feed
			if s.Config.UglyUrls {
				n.Url = Urlize(section + ".xml")
			} else {
				n.Url = Urlize(section + "/" + "index.xml")
			}
			n.Permalink = template.HTML(string(n.Site.BaseUrl) + n.Url)
			y := s.NewXMLBuffer()
			s.Tmpl.ExecuteTemplate(y, "rss.xml", n)
			s.WritePublic(section+slash+"index.xml", y.Bytes())
		}
	}
	return nil
}

示例#23
文件: templatefunc_test.go 项目: happyluo/beego

func TestRenderForm(t *testing.T) {
	type user struct {
		Id    int         `form:"-"`
		tag   string      `form:"tag"`
		Name  interface{} `form:"username"`
		Age   int         `form:"age,text,年龄:"`
		Sex   string
		Email []string
		Intro string `form:",textarea"`
	}

	u := user{Name: "test"}
	output := RenderForm(u)
	if output != template.HTML("") {
		t.Errorf("output should be empty but got %v", output)
	}
	output = RenderForm(&u)
	result := template.HTML(
		`Name: <input name="username" type="text" value="test"></br>` +
			`年龄:<input name="age" type="text" value="0"></br>` +
			`Sex: <input name="Sex" type="text" value=""></br>` +
			`Intro: <input name="Intro" type="textarea" value="">`)
	if output != result {
		t.Errorf("output should equal `%v` but got `%v`", result, output)
	}
}

示例#24
文件: ProductList.go 项目: elivoa/gotapestry

// returns a string contains available size and color.
func (p *ProductList) ShowSpecification(product *model.Product) template.HTML {
	if nil == product {
		return template.HTML("ERROR: PRODUCT IS NIL!")
	}

	var spec bytes.Buffer
	if product.Colors != nil {
		for idx, color := range product.Colors {
			if idx > 0 {
				spec.WriteString(", ")
			}
			spec.WriteString(color)
		}
	}
	if product.Sizes != nil {
		spec.WriteString("<span class=\"vline\">|</span>")
		for idx, size := range product.Sizes {
			if idx > 0 {
				spec.WriteString(", ")
			}
			spec.WriteString(size)
		}
	}
	return template.HTML(spec.String())
}

示例#25
文件: site.go 项目: hugo-2013-07-29/hugo-2013-07-29

func (s *Site) RenderHomePage() {
	n := s.NewNode()
	n.Title = n.Site.Title
	n.Url = Urlize(string(n.Site.BaseUrl))
	n.RSSlink = template.HTML(MakePermalink(string(n.Site.BaseUrl), string("index.xml")))
	n.Permalink = template.HTML(string(n.Site.BaseUrl))
	n.Date = s.Pages[0].Date
	if len(s.Pages) < 9 {
		n.Data["Pages"] = s.Pages
	} else {
		n.Data["Pages"] = s.Pages[:9]
	}
	x := s.RenderThing(n, "index.html")
	s.WritePublic("index.html", x.Bytes())

	if a := s.Tmpl.Lookup("rss.xml"); a != nil {
		// XML Feed
		n.Url = Urlize("index.xml")
		n.Title = "Recent Content"
		n.Permalink = template.HTML(string(n.Site.BaseUrl) + "index.xml")
		y := s.NewXMLBuffer()
		s.Tmpl.ExecuteTemplate(y, "rss.xml", n)
		s.WritePublic("index.xml", y.Bytes())
	}
}

示例#26
文件: tiny.go 项目: elitecodegroovy/GolangBestPractice

func schedule(w http.ResponseWriter, r *http.Request) {
	fmt.Println("Request to /schedule")
	params := mux.Vars(r)
	name := params["name"]
	time := params["hour"]
	timeVal, _ := strconv.ParseInt(time, 10, 0)
	intTimeVal := int(timeVal)
	createURL := "/register/" + name

	if _, ok := Users[name]; ok {
		if Users[name].Times[intTimeVal] == true {
			mutex.Lock()
			Users[name].Times[intTimeVal] = false
			mutex.Unlock()
			fmt.Println("User exists, variable should be modified")
			t, _ := template.ParseFiles("generic.txt")
			page := &Page{Title: "Successfully Scheduled!",
				Body: template.HTML("This appointment has been scheduled. <a href='/users'>Back to users</a>")}
			t.Execute(w, page)
		} else {
			fmt.Println("User exists, spot is taken!")
			t, _ := template.ParseFiles("generic.txt")
			page := &Page{Title: "Booked!",
				Body: template.HTML("Sorry, " + name + " is booked for" + time + " <a href='/users'>Back to users</a>")}
			t.Execute(w, page)
		}
	} else {
		fmt.Println("User does not exist")
		t, _ := template.ParseFiles("generic.txt")
		page := &Page{Title: "User Does Not Exist!", Body: template.HTML("Sorry, that user does not exist. Click <a href='" + createURL + "'>here</a> to create it. <a href='/users'>Back to users</a>")}
		t.Execute(w, page)
	}
	fmt.Println(name, time)
}

示例#27
文件: func_map.go 项目: kennylixi/qor

func (context *Context) LinkTo(text interface{}, link interface{}) template.HTML {
	text = reflect.Indirect(reflect.ValueOf(text)).Interface()
	if linkStr, ok := link.(string); ok {
		return template.HTML(fmt.Sprintf(`<a href="%v">%v</a>`, linkStr, text))
	}
	return template.HTML(fmt.Sprintf(`<a href="%v">%v</a>`, context.UrlFor(link), text))
}

示例#28
文件: page.go 项目: grafikdb/grafik-public

// RenderSource renders the source Markdown file.
// TODO: Add syntax highlighting with CodeMirror, see
// http://stackoverflow.com/questions/5521137/codemirror-2-highlight-only-no-editor
func (p *Page) RenderSource() template.HTML {
	const keyword = "\n<code><span>%s: </span>%s"

	if p == nil {
		return template.HTML("")
	} else if p.Err != nil {
		return template.HTML(fmt.Sprintf("
Page rendering error: %s
", p.Err)) } b := new(bytes.Buffer) for _, el := range p.Elements { switch el.typ { case markdownType: fmt.Fprintf(b, "%s", el.content) case queryType: fmt.Fprintf(b, "---\n%s", el.query.SQL) if param := el.query.Parameters(); param != "" { fmt.Fprintf(b, "\n===\n%s\n---\n", strings.TrimSpace(param)) } else { fmt.Fprintf(b, "---\n") } case includeType: fmt.Fprintf(b, keyword, "INCLUDE", el.name) case sourceType: fmt.Fprintf(b, keyword, "SOURCE", el.name) case tabType: fmt.Fprintf(b, keyword, "TAB", el.name) fmt.Fprintf(b, "%s", el.page.RenderSource()) case panelType: fmt.Fprintf(b, keyword, "PANEL", el.name) fmt.Fprintf(b, "%s", el.page.RenderSource()) } } return template.HTML(b.Bytes()) }

示例#29
文件: template_funcs.go 项目: iswarezwp/hugo

func refPage(page interface{}, ref, methodName string) template.HTML {
	value := reflect.ValueOf(page)

	method := value.MethodByName(methodName)

	if method.IsValid() && method.Type().NumIn() == 1 && method.Type().NumOut() == 2 {
		result := method.Call([]reflect.Value{reflect.ValueOf(ref)})

		url, err := result[0], result[1]

		if !err.IsNil() {
			jww.ERROR.Printf("%s", err.Interface())
			return template.HTML(fmt.Sprintf("%s", err.Interface()))
		}

		if url.String() == "" {
			jww.ERROR.Printf("ref %s could not be found\n", ref)
			return template.HTML(ref)
		}

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

	jww.ERROR.Printf("Can only create references from Page and Node objects.")
	return template.HTML(ref)
}

示例#30
文件: templates.go 项目: ernestoalejo/gaelib

func init() {
	// Compare two items to see if they're equal
	AddTemplateFunc("equals", func(a, b interface{}) bool {
		return a == b
	})

	// Returns true if the current iteration is the last one of the loop
	AddTemplateFunc("last", func(max, i int) bool {
		return i == max-1
	})

	// Quick format for a date & time
	AddTemplateFunc("datetime", func(t time.Time) string {
		return t.Format("02/01/2006 15:04:05")
	})

	// Convert any string into an HTML snnipet
	// Take care of not introducing a security error
	AddTemplateFunc("bhtml", func(s string) template.HTML {
		return template.HTML(s)
	})

	// Converts new lines to their equivalent in HTML
	AddTemplateFunc("nl2br", func(s string) template.HTML {
		s = html.EscapeString(s)
		s = strings.Replace(s, "\n", "<br>", -1)
		return template.HTML(s)
	})
}

展开阅读全文