tpls

Extendable, Fast Template Engine for Go
git clone git://git.lair.cx/tpls
Log | Files | Refs | README | LICENSE

builtin.go (1061B)


      1 package tplc
      2 
      3 import (
      4 	"bytes"
      5 	"fmt"
      6 	"io"
      7 
      8 	"go.lair.cx/go-core/net/htmlx"
      9 )
     10 
     11 func getBodyFromTextOnlyTag(t *htmlx.Tokenizer, name string, allowEmpty bool) ([]byte, error) {
     12 	if t.CurrentType() == htmlx.SelfClosingTagToken {
     13 		if allowEmpty {
     14 			return nil, nil
     15 		}
     16 		return nil, fmt.Errorf("self-closing tag but empty is not allowed for %s", name)
     17 	}
     18 
     19 	var buf []byte
     20 
     21 	t.SetRawTag(name)
     22 
     23 	for {
     24 		switch t.Next() {
     25 		case htmlx.TextToken:
     26 			buf = bytes.TrimSpace(t.Text())
     27 
     28 		case htmlx.EndTagToken:
     29 			if tagName, _ := t.TagName(); string(tagName) != name {
     30 				return nil, fmt.Errorf(
     31 					"%s: unexpected closing tag: %s",
     32 					name, tagName,
     33 				)
     34 			}
     35 			if !allowEmpty && len(buf) == 0 {
     36 				return nil, fmt.Errorf("empty content is not allowed for %s", name)
     37 			}
     38 			return buf, nil
     39 
     40 		case htmlx.ErrorToken:
     41 			err := t.Err()
     42 			if err == io.EOF {
     43 				return nil, io.ErrUnexpectedEOF
     44 			}
     45 			return nil, err
     46 
     47 		default:
     48 			return nil, fmt.Errorf(
     49 				"invalid %s syntax: unexpected token %s",
     50 				name,
     51 				t.CurrentType().String(),
     52 			)
     53 		}
     54 	}
     55 }