github.com/golazy/golazy@v0.0.7-0.20221012133820-968fe65a0b65/lazyview/nodes/attr.go (about) 1 package nodes 2 3 import ( 4 "bytes" 5 "io" 6 "strings" 7 ) 8 9 // Attr holds information about an attribute for an Element Node 10 type Attr struct { 11 key string 12 prop *string 13 } 14 15 // NewAttr creates a new attribute. 16 // If several arguments are given, they are join by a space 17 func NewAttr(key string, value ...string) Attr { 18 if len(value) == 0 { 19 return Attr{key: key} 20 } 21 a := strings.Join(value, " ") 22 return Attr{key: key, prop: &a} 23 } 24 25 // WriteTo writes the current string to the writer w 26 func (a Attr) WriteTo(w io.Writer) (n int64, err error) { 27 28 //Otherwise, the quotation marks are really needed only if the attribute 29 //value contains a space, a line break, an Ascii quotation mark ("), an 30 //Ascii apostrophe ('), a grave accent (`), an equals sign (=), a less than 31 //sign (<), or a greater than sign (>) 32 33 n16, err := w.Write([]byte(a.key)) 34 if err != nil || a.prop == nil { 35 return int64(n16), err 36 } 37 quote := "" 38 39 if len(*a.prop) == 0 || strings.ContainsAny(*a.prop, "\"'`=<> ") { 40 quote = `"` 41 } 42 n = int64(n16) 43 44 n16, err = w.Write([]byte("=" + quote)) 45 n += int64(n16) 46 if err != nil { 47 return n, err 48 } 49 50 s := strings.ReplaceAll(*a.prop, "\"", """) 51 s = strings.ReplaceAll(s, "<", "<") 52 s = strings.ReplaceAll(s, "\"", """) 53 s = strings.ReplaceAll(s, "&", "&") 54 55 n16, err = w.Write([]byte(s)) 56 n += int64(n16) 57 if err != nil { 58 return n, err 59 } 60 61 n16, err = w.Write([]byte(quote)) 62 n += int64(n16) 63 return n, err 64 } 65 66 func (a Attr) String() string { 67 w := &bytes.Buffer{} 68 a.WriteTo(w) 69 return w.String() 70 }