package tpp import ( //"fmt" "bytes" "context" ) type Preprocessor struct { tengo *Tengo tags [2][]byte preTag byte } // Get the new preprocessor with default options. func New(tengo *Tengo ) *Preprocessor { pp := &Preprocessor{} pp.tengo = tengo pp.tags = [2][]byte{ []byte("{{"), []byte("}}"), } pp.preTag = '#' return pp } func (pp *Preprocessor) Process( ctx context.Context, recompile bool, filePath string, data []byte, ) ([]byte, error) { var b bytes.Buffer preCodes := [][]byte{} texts := [][]byte{} codes := [][]byte{} for { idxStart := bytes.Index(data, pp.tags[0]) idxEnd := bytes.Index(data, pp.tags[1]) //fmt.Printf("cock %d %d %d\n", last, idxStart, idxEnd) if idxStart < 0 { if idxEnd >= 0 { return nil, UnexpectedError{ What: "end tag", } } texts = append(texts, data) break } else if idxEnd < 0 { return nil, UnexpectedError{ What: "start tag", } } text := data[:idxStart] texts = append(texts, text) code := data[idxStart+len(pp.tags[0]):idxEnd] if len(code) > 0 && code[0] == pp.preTag { code = code[1:] preCodes = append(preCodes, code) } else { codes = append(codes, code) } data = data[idxEnd + len(pp.tags[1]):] /*if len(data) > 0 && data[0] == '\n' { data = data[1:] }*/ } codeRets, err := pp.tengo.Eval( ctx, recompile, filePath, preCodes, codes, ) if err != nil { return nil, err } for i, codeRet := range codeRets { b.Write(texts[i]) b.Write(codeRet) } b.Write(texts[len(codeRets)]) return b.Bytes(), nil }