我有一个Go文本/模板来渲染一个文件,但是我发现很难在保留输出中的换行符的同时干净地构造模板。删除一个golang作家的连续空行
我想在模板中增加额外的不必要的换行符,使其更具可读性,但将它们从输出中去除。任何比正常段落中断更多的换行符都应该缩写为正常的段落中断,例如,
lines with
too many breaks should become lines with
normal paragraph breaks.
字符串可能太大而不能安全地存储在内存中,所以我想保留它作为输出流。
我第一次尝试:
type condensingWriter struct {
writer io.Writer
lastLineIsEmpty bool
}
func (c condensingWriter) Write(b []byte) (n int, err error){
thisLineIsEmpty := strings.TrimSpace(string(b)) == ""
defer func(){
c.lastLineIsEmpty = thisLineIsEmpty
}()
if c.lastLineIsEmpty && thisLineIsEmpty{
return 0, nil
} else {
return c.writer.Write(b)
}
}
这不工作,因为我天真地认为,这将缓冲的换行符,但事实并非如此。
有关如何使其发挥作用的任何建议?
也许用这个游戏作为一个起点: – Alex 2015-02-05 20:29:27
HTTP ://play.golang.org/p/wNtHFHobhm – Alex 2015-02-05 20:35:04
定义太大。 – 2015-02-05 20:41:18