HStringTemplate is a Haskell-ish port of the Java StringTemplate library written by Terrence Parr. It can be used for any templating purpose, but is often used for dynamically generated web pages.
Additional helper functions for HStringTemplate can be found in the HStringTemplateHelpers package
This is a stub page, which aims to supplement the API docs with tutorial style documentation.
1 Getting started
Assuming you have installed the library, try the following at a GHCi prompt:
Prelude> :m + Text.StringTemplate Prelude Text.StringTemplate> let t = newSTMP "Hello $name$" :: StringTemplate String
This has created a 'String' based StringTemplate. StringTemplates can be based around any 'Stringable' type, allowing you to use ByteString's or any other type if you write the Stringable instance. The template has a single 'hole' in it called 'name', delimited by dollar signs.
We can now fill in the hole using 'setAttribute', and render it to its base type (String in this case):
Prelude Text.StringTemplate> render $ setAttribute "name" "Joe" t "Hello Joe"
Instead of "Joe", we can use anything that has a ToSElem instance
2 Using data structures and generics
2.1 Using GenericStandard
2.2 Using GenericWithClass
3 Supported syntax
4 Loading templates
You will probably want to load templates from the file system instead of embedding them into Haskell source files. To do this:
- Create a directory to store the templates
- Create a template in it with the extension ".st" e.g "mytemplate.st"
- Load the template like the following example code:
import Data.ByteString.Lazy (ByteString) import Text.StringTemplate import Maybe (fromJust) main = do templates <- directoryGroup "/path/to/your/templates/" :: IO (STGroup ByteString) let t = fromJust $ getStringTemplate "mytemplate" templates print $ render t
If you have IO errors or the template does not exist, you will get an exception — error handling code is left as an excercise for the reader...
The type of directoryGroup result has to be specified, otherwise it does not know what type of StringTemplate to return. We have specified ByteString because the file system really stores byte streams, and we want to load the file uninterpreted (Haskell libraries do not just "do the right thing" with encodings, since in general that is not possible).