Adding custom template functions

Author Topic
mysh

Posted on

You can define new functions in /web/handler/tpl.go.

Example

Let's say we want to add an option to unsafely render some HTML. Open /web/handler/tpl.go and find the following section:

func (h *Handler) initTpl() {
	commonTemplates := ""
	for _, content := range TplCommonMap {
		commonTemplates += content
	}

	for name, content := range TplMap {
		views[name] = template.Must(template.New("main").Funcs(template.FuncMap{
			"hasPermission": func(name string) bool {
				return false
			},
			"logged": func() bool {
				return false
			},
			"syntax": func(input string) template.HTML {
				return template.HTML(syntax.Convert(input, true))
			},
			"sig": func(input string) template.HTML {
				return template.HTML(syntax.Convert(input, false))
			},
			"iso8601": func(t time.Time) string {
				return t.Format("2006-01-02")
			},
			"iso8601Time": func(t time.Time) string {
				return t.Format("2006-01-02 15:04:05")
			},
			"html": func(s string) template.HTML {
				return template.HTML(s)
			},
			"timeAgo": func(t time.Time) string {
				d := time.Since(t)
				if d.Seconds() < 60 {
					seconds := int(d.Seconds())
					if seconds == 1 {
						return "1 second ago"
					}
					return fmt.Sprintf("%d seconds ago", seconds)
				} else if d.Minutes() < 60 {
					minutes := int(d.Minutes())
					if minutes == 1 {
						return "1 minute ago"
					}
					return fmt.Sprintf("%d minutes ago", minutes)
				} else if d.Hours() < 24 {
					hours := int(d.Hours())
					if hours == 1 {
						return "1 hour ago"
					}
					return fmt.Sprintf("%d hours ago", hours)
				} else if d.Hours() < 730 {
					days := int(d.Hours()) / 24
					if days == 1 {
						return "1 day ago"
					}
					return fmt.Sprintf("%d days ago", days)
				} else if d.Hours() < 8760 {
					months := int(d.Hours()) / 730
					if months == 1 {
						return "1 month ago"
					}
					return fmt.Sprintf("%d months ago", months)
				} else {
					years := int(d.Hours()) / 8760
					if years == 1 {
						return "1 year ago"
					}
					return fmt.Sprintf("%d years ago", years)
				}
			},
			"inc": func(v int64) int64 {
				return v + 1
			},
			"dec": func(v int64) int64 {
				return v - 1
			},
		}).Parse(commonTemplates + content))
	}
}

To it we can now add something like this:

			"unsafeHtml": func(html string) template.HTML {
				return template.HTML(html)
			},

Then we can use {{ unsafeHtml "<b> this is bold </b>" }} to render some bold text in an unsafe way.

Last edited on