# 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