summaryrefslogtreecommitdiff
path: root/src/lib/template/format.go
blob: 4fb5393b94bd88e92d7820fe407f15d360f0175d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

// Template library: default formatters

package template

import (
	"fmt";
	"io";
	"reflect";
)

// StringFormatter formats into the default string representation.
// It is stored under the name "str" and is the default formatter.
// You can override the default formatter by storing your default
// under the name "" in your custom formatter map.
func StringFormatter(w io.Writer, value interface{}, format string) {
	fmt.Fprint(w, value);
}


var esc_amp = io.StringBytes("&")
var esc_lt = io.StringBytes("<")
var esc_gt = io.StringBytes(">")

// HtmlEscape writes to w the properly escaped HTML equivalent
// of the plain text data s.
func HtmlEscape(w io.Writer, s []byte) {
	last := 0;
	for i, c := range s {
		if c == '&' || c == '<' || c == '>' {
			w.Write(s[last:i]);
			switch c {
			case '&':
				w.Write(esc_amp);
			case '<':
				w.Write(esc_lt);
			case '>':
				w.Write(esc_gt);
			}
			last = i+1;
		}
	}
	w.Write(s[last:len(s)]);
}

// HtmlFormatter formats arbitrary values for HTML
func HtmlFormatter(w io.Writer, value interface{}, format string) {
	var b io.ByteBuffer;
	fmt.Fprint(&b, value);
	HtmlEscape(w, b.Data());
}