# Haskell, <s>139</s> 135 bytes s#p=j$foldl g("",0)s where g(a,n)c|c=='|'=(j(a,n)++"\n"++q n,n)|1>0=(a++[c],n+1);q m=' '<$[1..m];j(a,n)=a++q(sum[1|c<-s,c/='|']-n+1)++p Saved 4 bytes by inlining a definition. **Ungolfed:** template :: String -> String -> String template code comment = format $ foldl g ("", 0) code where g (acc, n) c | c == '|' = (format (acc, n) ++ "\n" ++ spaces n, n) | otherwise = (acc ++ [c], n+1) l = length $ filter (/= '|') code spaces n = replicate n ' ' format (acc, n) = acc ++ spaces (l-n+1) ++ comment