We’re rewarding the question askers & reputations are being recalculated! Read more.
2 Inline the definition of `l`
source | link

Haskell, 139139 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);l=sum[1|c<-s,c/='|'];q;q m=' '<$[1..m];j(a,n)=a++q(lsum[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

Haskell, 139 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);l=sum[1|c<-s,c/='|'];q m=' '<$[1..m];j(a,n)=a++q(l-n+1)++p

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

Haskell, 139 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
1
source | link

Haskell, 139 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);l=sum[1|c<-s,c/='|'];q m=' '<$[1..m];j(a,n)=a++q(l-n+1)++p

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