Merge from mainline (167278:168000).
[official-gcc/graphite-test-results.git] / libgo / go / template / format.go
blob8a31de970a3af28bf12249e1e100ea01f081ac8e
1 // Copyright 2009 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
5 // Template library: default formatters
7 package template
9 import (
10 "bytes"
11 "fmt"
12 "io"
15 // StringFormatter formats into the default string representation.
16 // It is stored under the name "str" and is the default formatter.
17 // You can override the default formatter by storing your default
18 // under the name "" in your custom formatter map.
19 func StringFormatter(w io.Writer, value interface{}, format string) {
20 if b, ok := value.([]byte); ok {
21 w.Write(b)
22 return
24 fmt.Fprint(w, value)
27 var (
28 esc_quot = []byte(""") // shorter than """
29 esc_apos = []byte("'") // shorter than "'"
30 esc_amp = []byte("&")
31 esc_lt = []byte("<")
32 esc_gt = []byte(">")
35 // HTMLEscape writes to w the properly escaped HTML equivalent
36 // of the plain text data s.
37 func HTMLEscape(w io.Writer, s []byte) {
38 var esc []byte
39 last := 0
40 for i, c := range s {
41 switch c {
42 case '"':
43 esc = esc_quot
44 case '\'':
45 esc = esc_apos
46 case '&':
47 esc = esc_amp
48 case '<':
49 esc = esc_lt
50 case '>':
51 esc = esc_gt
52 default:
53 continue
55 w.Write(s[last:i])
56 w.Write(esc)
57 last = i + 1
59 w.Write(s[last:])
62 // HTMLFormatter formats arbitrary values for HTML
63 func HTMLFormatter(w io.Writer, value interface{}, format string) {
64 b, ok := value.([]byte)
65 if !ok {
66 var buf bytes.Buffer
67 fmt.Fprint(&buf, value)
68 b = buf.Bytes()
70 HTMLEscape(w, b)