Ejemplo n.º 1
0
func (s *SprocketsDirectory) GetAssetUrl(name string) (template.HTMLAttr, error) {
	src, ok := s.assets[name]
	if !ok {
		return template.HTMLAttr(s.prefix + "__NOT_FOUND__" + name), errors.New("Asset not found: " + name)
	}
	return template.HTMLAttr(s.prefix + src), nil
}
Ejemplo n.º 2
0
// NewTagEntry creates a new ArchiveEntry for the given values.
func NewTagEntry(file, title string) *TagEntry {
	url := file + ".html"

	// Not all pages have a metadata title defined.
	// Use the page url instead, after we prettify it a bit.
	if len(title) == 0 {
		title = file

		if strings.HasSuffix(title, "/index") {
			title, _ = filepath.Split(title)
		}

		if title == "/" {
			title = "Home"
		}
	}

	// If the url ends with /index.html, we strip off the index part.
	// It just takes up unnecessary bytes in the output and
	// `foo/bar/` looks better than `foo/bar/index.html`.
	if strings.HasSuffix(url, "/index.html") {
		url, _ = filepath.Split(url)
	}

	te := new(TagEntry)
	te.Url = template.HTMLAttr(url)
	te.Title = template.HTMLAttr(title)
	return te
}
Ejemplo n.º 3
0
func (s *SprocketsServer) GetAssetUrl(name string) (template.HTMLAttr, error) {
	src, ok := s.assets[name]
	if !ok {
		return template.HTMLAttr(s.baseUrl + "__NOT_FOUND__" + name), errors.New("Asset not found: " + name)
	}
	return template.HTMLAttr(s.baseUrl + src), nil
}
Ejemplo n.º 4
0
func InjectRender(c *web.C, h http.Handler) http.Handler {
	fn := func(w http.ResponseWriter, r *http.Request) {

		c.Env["render"] = render.New(render.Options{
			Directory:  "views",
			Layout:     "",
			Extensions: []string{".tmpl"},
			Funcs: []template.FuncMap{template.FuncMap{
				"classIfHere": func(path, class string) template.HTMLAttr {
					if r.URL.Path == path {
						return template.HTMLAttr(fmt.Sprintf(`class="%s"`, class))
					}
					return template.HTMLAttr("")
				},
				"date": func(date time.Time) string {
					return date.Format("January 2, 2006")
				},
				"checkIfInArray": func(x string, slice []string) template.HTMLAttr {
					for _, y := range slice {
						if x == y {
							return template.HTMLAttr("checked")
						}
					}
					return template.HTMLAttr("")
				},
			}},
		})

		h.ServeHTTP(w, r)

	}

	return http.HandlerFunc(fn)
}
Ejemplo n.º 5
0
func EchoSelectSelected(option string, value interface{}) htmlTemplate.HTMLAttr {
	if option == fmt.Sprint(value) {
		return htmlTemplate.HTMLAttr(" selected")
	}

	return htmlTemplate.HTMLAttr("")
}
Ejemplo n.º 6
0
// NewArchiveEntry creates a new ArchiveEntry for the given values.
func NewArchiveEntry(file, title, desc string, stamp time.Time) *ArchiveEntry {
	url := file + ".html"

	// Not all pages have a metadata title defined.
	// Use the page url instead, after we prettify it a bit.
	if len(title) == 0 {
		title = file

		if strings.HasSuffix(title, "/index") {
			title, _ = filepath.Split(title)
		}

		if title == "/" {
			title = "Home"
		}
	}

	// If the url ends with /index.html, we strip off the index part.
	// It just takes up unnecessary bytes in the output and
	// `foo/bar/` looks better than `foo/bar/index.html`.
	if strings.HasSuffix(url, "/index.html") {
		url, _ = filepath.Split(url)
	}

	ae := new(ArchiveEntry)
	ae.Url = template.HTMLAttr(url)
	ae.Title = template.HTMLAttr(title)
	ae.Description = template.HTMLAttr(desc)
	ae.Stamp = stamp
	return ae
}
Ejemplo n.º 7
0
func (ep EnumParam) EnumClassAttr(named, classif string, optelse ...string) (template.HTMLAttr, error) {
	classelse, err := EnumClassAttrArgs(optelse)
	if err != nil {
		return template.HTMLAttr(""), err
	}
	_, uptr := ep.EnumDecodec.Unew()
	if err := uptr.Unmarshal(named, new(bool)); err != nil {
		return template.HTMLAttr(""), err
	}
	if ep.Number.Uint != uptr.Touint() {
		classif = classelse
	}
	return SprintfAttr(" class=%q", classif), nil
}
Ejemplo n.º 8
0
func (n Nota) EnumClassAttr(named, classif string, optelse ...string) (template.HTMLAttr, error) {
	classelse, err := params.EnumClassAttrArgs(optelse)
	if err != nil {
		return template.HTMLAttr(""), err
	}
	eparams := params.NewParamsENUM(nil)
	ed := eparams[n.Base()].EnumDecodec
	_, uptr := ed.Unew()
	if err := uptr.Unmarshal(named, new(bool)); err != nil {
		return template.HTMLAttr(""), err
	}
	return SprintfAttr(" className={(%s.Uint == %d) ? %q : %q}",
		n, uptr.Touint(), classif, classelse), nil
}
Ejemplo n.º 9
0
func UserTFAPage(w http.ResponseWriter, req *http.Request) {
	args := handlers.GetArgs(req)

	u := quimby.NewUser(args.Vars["username"], quimby.UserDB(args.DB), quimby.UserTFA(handlers.TFA))
	if err := u.Fetch(); err != nil {
		context.Set(req, "error", err)
		return
	}

	qrData, err := u.UpdateTFA()
	if err != nil {
		context.Set(req, "error", err)
		return
	}

	if _, err := u.Save(); err != nil {
		context.Set(req, "error", err)
		return
	}

	qr := qrPage{
		userPage: userPage{
			User:  args.User.Username,
			Admin: handlers.Admin(args),
			Links: []link{
				{"quimby", "/"},
				{"admin", "/admin.html"},
			},
		},
		QR: template.HTMLAttr(base64.StdEncoding.EncodeToString(qrData)),
	}
	templates["qr-code.html"].template.ExecuteTemplate(w, "base", qr)
}
Ejemplo n.º 10
0
func EchoActiveLink(link_href string) htmlTemplate.HTMLAttr {
	if strings.Contains(active_page, link_href) {
		return htmlTemplate.HTMLAttr(" class=\"active\"")
	}

	return ""
}
Ejemplo n.º 11
0
func (b Bool) BoolClassAttr(fstclass, sndclass string) template.HTMLAttr {
	s := fstclass
	if !b {
		s = sndclass
	}
	return template.HTMLAttr(fmt.Sprintf(" class=%q", s))
}
Ejemplo n.º 12
0
func (f *Field) Data() map[string]interface{} {
	safeParams := make(map[template.HTMLAttr]interface{})
	for k, v := range f.params {
		safeParams[template.HTMLAttr(k)] = v
	}
	data := map[string]interface{}{
		"classes":      f.class,
		"id":           f.id,
		"name":         f.name,
		"params":       safeParams,
		"css":          f.css,
		"type":         f.fieldType,
		"label":        f.label,
		"labelClasses": f.labelClass,
		"tags":         f.tag,
		"value":        f.value,
		"helptext":     f.helptext,
		"errors":       f.errors,
		"container":    "form",
		"choices":      f.choices,
	}
	for k, v := range f.additionalData {
		data[k] = v
	}
	for k, v := range f.AppendData {
		data[k] = v
	}
	return data
}
Ejemplo n.º 13
0
// safeHTMLAttr returns the attribute an HTML element as k=v.
// If v contains double quotes "", the attribute value will be wrapped
// in single quotes '', and vice versa. Defaults to double quotes.
func safeHTMLAttr(k, v string) html.HTMLAttr {
	q := `"`
	if strings.ContainsRune(v, '"') {
		q = "'"
	}
	return html.HTMLAttr(k + "=" + q + v + q)
}
Ejemplo n.º 14
0
func createLiveBlogSample(newStatus int, timestamp time.Time, firstBlogID string, originSource string, page Page) LiveBlogSample {
	if newStatus > len(blogs) {
		newStatus = len(blogs)
	}
	blogItems := getBlogEntries(newStatus, timestamp)
	score := createScore(newStatus, 0)
	firstItemIndex := getBlogEntryIndexFromID(firstBlogID, blogItems)
	lenghtCurrentPageBlog := int(math.Min(float64(len(blogItems)), float64(firstItemIndex+MAX_BLOG_ITEMS_NUMBER_PER_PAGE)))

	urlPrefix := buildPrefixPaginationURL(originSource, page)
	nextPageId := getNextPageId(blogItems, firstItemIndex+MAX_BLOG_ITEMS_NUMBER_PER_PAGE)
	previousPageId := getPrevPageId(firstItemIndex)
	nextPageUrl := buildPaginationURL(urlPrefix, nextPageId)
	prevPageUrl := buildPaginationURL(urlPrefix, previousPageId)
	disabled := ""
	if prevPageUrl != "" {
		disabled = "disabled"
	}
	blogMetadata, _ := json.MarshalIndent(createMetadata(originSource), "        ", "  ")

	return LiveBlogSample{BlogItems: blogItems[firstItemIndex:lenghtCurrentPageBlog],
		FootballScore: score,
		BlogMetadata:  template.JS(blogMetadata),
		NextPageURL:   nextPageUrl,
		PrevPageURL:   prevPageUrl,
		PageNumber:    getPageNumberFromProductIndex(firstItemIndex),
		Disabled:      template.HTMLAttr(disabled)}
}
Ejemplo n.º 15
0
func init() {
	HtmlFuncBoot.Register(func(w *Web) {
		// HTML Marksafe
		w.HtmlFunc["html"] = func(str string) html.HTML {
			return html.HTML(str)
		}

		// HTML Attr MarkSafe
		w.HtmlFunc["htmlattr"] = func(str string) html.HTMLAttr {
			return html.HTMLAttr(str)
		}

		// JS Marksafe
		w.HtmlFunc["js"] = func(str string) html.JS {
			return html.JS(str)
		}

		// JS String Marksafe
		w.HtmlFunc["jsstr"] = func(str string) html.JSStr {
			return html.JSStr(str)
		}

		// CSS Marksafe
		w.HtmlFunc["css"] = func(str string) html.CSS {
			return html.CSS(str)
		}
	})
}
Ejemplo n.º 16
0
func TestEchoSelectSelected(t *testing.T) {
	Convey("Given option an value are not equal at all", t, func() {

		Convey("It should return empty HTMLAttr", func() {
			html_attr := htmlTemplate.HTMLAttr("")
			So(EchoSelectSelected("10", "foo"), ShouldEqual, html_attr)
		})
	})

	Convey("Given option an value are equal strings", t, func() {

		Convey("It should return 'selected' HTMLAttr", func() {
			html_attr := htmlTemplate.HTMLAttr(" selected")
			So(EchoSelectSelected("10", 10), ShouldEqual, html_attr)
		})
	})
}
Ejemplo n.º 17
0
func (vh *ViewHelper) StylesheetLinkTag(name string) (template.HTML, error) {
	var attr template.HTMLAttr
	url, err := vh.AssetPipeline.GetAssetUrl(name)
	if err != nil {
		return template.HTML(""), err
	}
	attr = template.HTMLAttr(url)
	return template.HTML(`<link href="` + template.HTMLEscaper(attr) + `" rel="stylesheet">`), nil
}
Ejemplo n.º 18
0
func (vh *ViewHelper) JavascriptTag(name string) (template.HTML, error) {
	var attr template.HTMLAttr
	url, err := vh.AssetPipeline.GetAssetUrl(name)
	if err != nil {
		return template.HTML(""), err
	}
	attr = template.HTMLAttr(url)
	return template.HTML(`<script src="` + template.HTMLEscaper(attr) + `" type="text/javascript"></script>`), nil
}
Ejemplo n.º 19
0
func TestEchoActiveLink(t *testing.T) {
	Convey("Given both active_page and link_href are simple slashes", t, func() {

		Convey("It should return an HTMLAttr", func() {
			active_page = "/"
			html_attr := htmlTemplate.HTMLAttr(" class=\"active\"")
			So(EchoActiveLink("/"), ShouldResemble, html_attr)
		})
	})

	Convey("Given active_page and link_href are the same", t, func() {

		Convey("It should return an HTMLAttr", func() {
			active_page = "/asd"
			html_attr := htmlTemplate.HTMLAttr(" class=\"active\"")
			So(EchoActiveLink("/asd"), ShouldResemble, html_attr)
		})
	})

	Convey("Given active_page contains link_href", t, func() {

		Convey("It should return an HTMLAttr", func() {
			active_page = "/asd"
			html_attr := htmlTemplate.HTMLAttr(" class=\"active\"")
			So(EchoActiveLink("/as"), ShouldResemble, html_attr)
		})
	})

	Convey("Given active_page and link_href are different", t, func() {

		Convey("It should return an empty string", func() {
			active_page = "/hdrf"
			So(EchoActiveLink("/td"), ShouldEqual, "")
		})
	})

	Convey("Given active_page does not contain all letters of link_href", t, func() {

		Convey("It should not return an empty string", func() {
			active_page = "/hdrf"
			So(EchoActiveLink("/hdrfas"), ShouldEqual, "")
		})
	})
}
Ejemplo n.º 20
0
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))
}
Ejemplo n.º 21
0
func (s *TagSetList) Append(doc *Document) {
	sets := *s
	tags := doc.Tags
	newtags := make([]string, 0, len(tags))

	// Add documents to existing tag sets.
outer:
	for len(tags) > 0 {
		for _, set := range sets {
			if string(set.Name) != tags[0] {
				continue
			}

			set.Pages = append(set.Pages, &TagEntry{
				Title: doc.SubTitle,
				Url:   template.HTMLAttr(doc.RelPath()),
			})

			sort.Sort(set.Pages)
			tags = tags[1:]
			continue outer
		}

		newtags = append(newtags, tags[0])
		tags = tags[1:]
	}

	// Some tags may be new. Create new sets for them.
	for _, tag := range newtags {
		sets = append(sets, &TagSet{
			Name: template.HTMLAttr(tag),
			Pages: TagEntryList{
				&TagEntry{
					Title: doc.SubTitle,
					Url:   template.HTMLAttr(doc.RelPath()),
				},
			},
		})
	}

	sort.Sort(sets)
	*s = sets
}
Ejemplo n.º 22
0
func configureAssets(m *mart.ClassicMartini, analyticsConfig AnalyticsConfig, logger boshlog.Logger) {
	assetsIDBytes, err := ioutil.ReadFile("./public/assets-id")
	ensureNoErr(logger, "Failed to find assets ID", err)

	assetsID := strings.TrimSpace(string(assetsIDBytes))

	assetsFuncs := template.FuncMap{
		"cssPath": func(fileName string) (string, error) {
			return "/" + assetsID + "/stylesheets/" + fileName, nil
		},
		"jsPath": func(fileName string) (string, error) {
			return "/" + assetsID + "/javascript/" + fileName, nil
		},
		"imgPath": func(fileName string) (string, error) {
			return "/" + assetsID + "/images/" + fileName, nil
		},
	}

	analyticsConfigFuncs := template.FuncMap{
		"analyticsConfig": func() AnalyticsConfig {
			return analyticsConfig
		},
	}

	htmlFuncs := template.FuncMap{
		"href": func(s string) template.HTMLAttr {
			return template.HTMLAttr(fmt.Sprintf(" href='%s' ", s))
		},
	}

	// Use prefix to cache bust images, stylesheets, and js
	m.Use(mart.Static(
		"./public",
		mart.StaticOptions{
			Prefix: assetsID,
		},
	))

	// Make sure docs' images are available as `docs/images/X`
	m.Use(mart.Static(
		"./templates/docs/images",
		mart.StaticOptions{
			Prefix: "docs/images",
		},
	))

	m.Use(martrend.Renderer(
		martrend.Options{
			Layout:     "layout",
			Directory:  "./templates",
			Extensions: []string{".tmpl", ".html"},
			Funcs:      []template.FuncMap{assetsFuncs, analyticsConfigFuncs, htmlFuncs},
		},
	))
}
Ejemplo n.º 23
0
// create an login url with specify redirect to param
func loginto(uris ...string) template.HTMLAttr {
	var uri string
	if len(uris) > 0 {
		uri = uris[0]
	}
	to := fmt.Sprintf("%slogin", setting.AppUrl)
	if len(uri) > 0 {
		to += "?to=" + url.QueryEscape(uri)
	}
	return template.HTMLAttr(to)
}
Ejemplo n.º 24
0
func (lp LimitParam) Encode(this *uint) template.HTMLAttr {
	if this == nil {
		this = &lp.Value
	}
	values := lp.Query.ValuesCopy()
	if *this != lp.LimitDecodec.Default {
		values.Set(lp.LimitDecodec.Pname, fmt.Sprintf("%d", *this))
	} else {
		values.Del(lp.LimitDecodec.Pname)
	}
	return template.HTMLAttr("?" + lp.Query.ValuesEncode(values))
}
Ejemplo n.º 25
0
func (la Linkattrs) Attrs(seq SEQ) template.HTMLAttr {
	attr := la.Attr(seq)
	line := ""

	for _, context := range []struct {
		Name  template.HTMLAttr
		Value string
	}{
		{Name: template.HTMLAttr("href"), Value: attr.Href},
		{Name: template.HTMLAttr("class"), Value: attr.Class},
	} {
		buf := new(bytes.Buffer)
		if err := attemplate.Execute(buf, context); err != nil {
			panic(err)
			return template.HTMLAttr("")
		}
		s := buf.String()
		line += s[2 : len(s)-2]
	}
	return template.HTMLAttr(line)
}
Ejemplo n.º 26
0
// A cool helper to encode a selection of sample images to be directly embedded into <img> tags
func (i *imageCollection) GetSampleImages() []template.HTMLAttr {
	imgs := []template.HTMLAttr{}
	for _, img := range i.library.GetSampleImages(9) {
		buf := &bytes.Buffer{}
		err := jpeg.Encode(buf, img, &jpeg.Options{30})
		if err != nil {
			return imgs
		}
		data := "src=data:image/jpg;base64," + base64.StdEncoding.EncodeToString(buf.Bytes())
		imgs = append(imgs, template.HTMLAttr(data))
	}
	return imgs
}
Ejemplo n.º 27
0
func UserForm(w http.ResponseWriter, req *http.Request) {
	args := handlers.GetArgs(req)

	err := req.ParseForm()
	if err != nil {
		context.Set(req, "error", err)
		return
	}

	username := args.Vars["username"]
	var u *quimby.User
	if username == "new-user" {
		u = quimby.NewUser(req.PostFormValue("username"), quimby.UserDB(args.DB), quimby.UserTFA(handlers.TFA))
		u.Password = req.PostFormValue("password")
		pw := req.PostFormValue("password_confirm")
		if pw != u.Password {
			context.Set(req, "error", ErrPasswordsDoNotMatch)
			return
		}
	} else {
		u = quimby.NewUser(username, quimby.UserDB(args.DB), quimby.UserTFA(handlers.TFA))
		if err := u.Fetch(); err != nil {
			context.Set(req, "error", ErrPasswordsDoNotMatch)
			return
		}
	}
	u.Permission = req.PostFormValue("permission")
	qrData, err := u.Save()
	if err != nil {
		context.Set(req, "error", err)
		return
	}
	if username == "new-user" {
		qr := qrPage{
			userPage: userPage{
				User:  args.User.Username,
				Admin: handlers.Admin(args),
				Links: []link{
					{"quimby", "/"},
					{"admin", "/admin.html"},
				},
			},
			QR: template.HTMLAttr(base64.StdEncoding.EncodeToString(qrData)),
		}
		templates["qr-code.html"].template.ExecuteTemplate(w, "base", qr)
	} else {
		w.Header().Set("Location", "/admin.html")
		w.WriteHeader(http.StatusFound)
	}
}
Ejemplo n.º 28
0
func InjectRender(c *web.C, h http.Handler) http.Handler {
	fn := func(w http.ResponseWriter, r *http.Request) {

		c.Env["render"] = render.New(render.Options{
			Directory:  "views",
			Layout:     "",
			Extensions: []string{".tmpl"},
			Funcs: []template.FuncMap{template.FuncMap{
				"classIfHere": func(path, class string) template.HTMLAttr {
					if r.URL.Path == path {
						return template.HTMLAttr(fmt.Sprintf(`class="%s"`, class))
					}
					return template.HTMLAttr("")
				},
				"classIfRootHere": func(path, class string) template.HTMLAttr {
					if strings.HasPrefix(r.URL.Path, path) {
						return template.HTMLAttr(fmt.Sprintf(`class="%s"`, class))
					}
					return template.HTMLAttr("")
				},
				"date": func(date time.Time) string {
					return date.Format("January 2, 2006")
				},
				"checkIfInArray": func(x string, slice []string) template.HTMLAttr {
					for _, y := range slice {
						if x == y {
							return template.HTMLAttr("checked")
						}
					}
					return template.HTMLAttr("")
				},
				"html": func(s string) template.HTML {
					return template.HTML(s)
				},
				"plusone": func(i int) int {
					return i + 1
				},
				"excerpt": func(str string, length int) string {
					if words := strings.Split(str, " "); len(words) > length {
						words = words[:length]
						return fmt.Sprintf("%s...", strings.Join(words, " "))
					}

					return str
				},
				"sprintf": func(f string, a ...interface{}) string {
					return fmt.Sprintf(f, a...)
				},
			}},
		})

		h.ServeHTTP(w, r)

	}

	return http.HandlerFunc(fn)
}
Ejemplo n.º 29
0
Archivo: init.go Proyecto: kdada/tinygo
func init() {
	//初始化基本模板函数
	//until(start, end int) []int:生成一个从start到end的数组
	//time(t time.Time) string:返回时间字符串2006-01-02 15:04:05
	//date(t time.Time) string:返回日期字符串2006-01-02
	//tocss(s string) template.CSS:转换字符串为CSS
	//tohtml(s string) template.HTML:转换字符串为HTML
	//toattr(s string) template.HTMLAttr:转换字符串为HTMLAttr
	//tojs(s string) template.JS:转换字符串为JS
	//tojsstr(s string) template.JSStr:转换字符串为JSStr
	//tourl(s string) template.URL:转换字符串为URL
	commonFuncMap = template.FuncMap{
		"until": func(start, end int) []int {
			if end >= start {
				var length = end - start + 1
				var result = make([]int, length)
				for i := 0; i < length; i++ {
					result[i] = start + i
				}
				return result
			}
			return []int{}
		},
		"time": func(t time.Time) string {
			return t.Format("2006-01-02 15:04:05")
		},
		"date": func(t time.Time) string {
			return t.Format("2006-01-02")
		},
		"tocss": func(s string) template.CSS {
			return template.CSS(s)
		},
		"tohtml": func(s string) template.HTML {
			return template.HTML(s)
		},
		"toattr": func(s string) template.HTMLAttr {
			return template.HTMLAttr(s)
		},
		"tojs": func(s string) template.JS {
			return template.JS(s)
		},
		"tojsstr": func(s string) template.JSStr {
			return template.JSStr(s)
		},
		"tourl": func(s string) template.URL {
			return template.URL(s)
		},
	}
}
Ejemplo n.º 30
0
func TestToString(t *testing.T) {
	var foo interface{} = "one more time"
	assert.Equal(t, ToString(8), "8")
	assert.Equal(t, ToString(int64(16)), "16")
	assert.Equal(t, ToString(8.12), "8.12")
	assert.Equal(t, ToString([]byte("one time")), "one time")
	assert.Equal(t, ToString(template.HTML("one time")), "one time")
	assert.Equal(t, ToString(template.URL("http://somehost.foo")), "http://somehost.foo")
	assert.Equal(t, ToString(template.JS("(1+2)")), "(1+2)")
	assert.Equal(t, ToString(template.CSS("a")), "a")
	assert.Equal(t, ToString(template.HTMLAttr("a")), "a")
	assert.Equal(t, ToString(foo), "one more time")
	assert.Equal(t, ToString(nil), "")
	assert.Equal(t, ToString(true), "true")
	assert.Equal(t, ToString(false), "false")
}