[Haskell] ANN: template 0.1 - Simple string substitution

Johan Tibell johan.tibell at gmail.com
Mon Apr 23 16:41:49 EDT 2007

As an exercise I wrote a simple string substitution library that supports
"$"-based substitution ala Perl or Python. Example usage:

> import qualified Data.ByteString.Lazy.Char8 as B
> import Text.Template
> context = Map.fromList . map packPair
>     where packPair (x, y) = (B.pack x, B.pack y)
> helloTemplate = B.pack "Hello, $name! Want some ${fruit}s?"
> helloContext = context [("name", "Johan"), ("fruit", "banana")]
> main = B.putStrLn $ substitute helloTemplate helloContext

Hopefully this is useful for someone who needs something more readable
than Text.Printf's "%s"-based substitution or string concatenation for
longer strings but less than a full blown templating system like the
ones found in most web frameworks.


darcs get http://darcs.johantibell.com/template

Once we get ByteString literals most of the noise in the above example
will disappear. In the mean time it's probably a good idea to write
utility function like "context" above when you prefer a convenient
String interface to a somewhat faster ByteString interface.

It would be great if someone could do a code review and add it to
Hackage if it looks OK. I'll really appreciate the feedback. Also, I'm
not 100% sure how to make the haddock links work with Hackage so they
link to the library docs. Is this something done at upload time?

Here are some open issues:

   * I currently use my own ByteString parser. Data.Binary almost does
what I need. Basically I need takeWhile and two chars of look-ahead.

   * I would like to only depend on base, currently I use State so I
depend on mtl.



More information about the Haskell mailing list