github.com/keysonZZZ/kmg@v0.0.0-20151121023212-05317bfd7d39/kmgView/JsTpl/JsTpl.go (about) 1 package JsTpl 2 3 import ( 4 "bytes" 5 "path/filepath" 6 7 "github.com/bronze1man/kmg/encoding/kmgJson" 8 "github.com/bronze1man/kmg/kmgFile" 9 ) 10 11 func MustBuildTplOneFile(in []byte) (out []byte) { 12 //把所有的`xxx` 转成 "xxx\xxx" 之类的,严格保留里面的所有字符串,暂时没有任何办法可以打出 ` 13 outbuf := &bytes.Buffer{} 14 thisHereDocBuf := &bytes.Buffer{} 15 isInHereDoc := false 16 for i := range in { 17 //进入heredoc 18 if !isInHereDoc && in[i] == '`' { 19 isInHereDoc = true 20 continue 21 } 22 //出heredoc 23 if isInHereDoc && in[i] == '`' { 24 isInHereDoc = false 25 outbuf.Write(kmgJson.MustMarshal(thisHereDocBuf.String())) 26 thisHereDocBuf.Reset() 27 continue 28 } 29 //不是heredoc的部分 30 if !isInHereDoc { 31 outbuf.WriteByte(in[i]) 32 continue 33 } 34 //是heredoc的部分 35 if isInHereDoc { 36 thisHereDocBuf.WriteByte(in[i]) 37 continue 38 } 39 } 40 if isInHereDoc { 41 panic("end with heredoc") 42 } 43 return outbuf.Bytes() 44 } 45 46 func MustBuildTplInDir(path string) { 47 pathList, err := kmgFile.GetAllFiles(path) 48 if err != nil { 49 panic(err) 50 } 51 for _, val := range pathList { 52 if filepath.Ext(val) != ".jst" { 53 continue 54 } 55 out := MustBuildTplOneFile(kmgFile.MustReadFile(val)) 56 outFilePath := kmgFile.PathTrimExt(val) + ".js" 57 kmgFile.MustWriteFile(outFilePath, out) 58 } 59 }